Tuesday, December 05, 2006

An introduction to R


R, a Programming Environment for Data Analysis and Graphics is used by many people as a statistics system - an environment within which many classical and modern statistical techniques have been implemented. A few of these are built into the base R environment, but many are supplied as packages. There are about 25 packages supplied with R (called “standard” and “recommended” packages) and many more are available through the CRAN family of Internet sites (via http://CRAN.R-project.org) and elsewhere. There is an important difference in philosophy between S (and hence R) and the other main statistical systems. In S a statistical analysis is normally done as a series of steps, with intermediate results being stored in objects. Thus whereas SAS and SPSS will give copious output from a regression or discriminant analysis, R will give minimal output and store the results in a fit object for subsequent interrogation by further R functions.

The most convenient way to use R is at a graphics workstation running a windowing system.
When you use the R program it issues a prompt when it expects input commands. The default prompt is ‘>’, which on UNIX might be the same as the shell prompt, and so it may appear that nothing is happening.

R has an inbuilt help facility similar to the man facility of UNIX. To get more information on any specific named function, for example solve, the command is
> help(solve)
An alternative is
> ?solve
> help("[[")
Either form of quote mark may be used to escape the other, as in the string "It’s important". Our convention is to use double quote marks for preference. On most R installations help is available in HTML format by running
> help.start()

Windows versions of R have other optional help systems: use
> ?help


R commands, case sensitivity, etc.
Technically R is an expression language with a very simple syntax. It is case sensitive as are most UNIX based packages, so A and a are different symbols and would refer to different variables. Normally all alphanumeric symbols are allowed1 (and in some countries this includes accented letters) plus ‘.’ and ‘_’, with the restriction that a name must start with ‘.’ or a letter, and if it starts with ‘.’ the second character must not be a digit.

Elementary commands consist of either expressions or assignments.

Commands are separated either by a semi-colon (‘;’), or by a newline. Elementary commands can be grouped together into one compound expression by braces (‘{’ and ‘}’). Comments can be put almost2 anywhere, starting with a hashmark (‘#’), everything to the end of the line is a comment.

If a command is not complete at the end of a line, R will give a different prompt, by default
+
on second and subsequent lines and continue to read input until the command is syntactically complete. This prompt may be changed by the user. We will generally omit the continuation prompt and indicate continuation by simple indenting.

The entities that R creates and manipulates are known as objects. These may be variables, arrays of numbers, character strings, functions, or more general structures built from such components.
During an R session, objects are created and stored by name (we discuss this process in the next session). The R command
> objects()
(alternatively, ls()) can be used to display the names of (most of) the objects which are currently stored within R. The collection of objects currently stored is called the workspace. To remove objects the function rm is available:
> rm(x, y, z, ink, junk, temp, foo, bar)

All objects created during an R sessions can be stored permanently in a file for use in future R sessions. At the end of each R session you are given the opportunity to save all the currently available objects. If you indicate that you want to do this, the objects are written to a file called ‘.RData’5 in the current directory, and the command lines used in the session are saved to a file called ‘.Rhistory’.

When R is started at later time from the same directory it reloads the workspace from this file. At the same time the associated commands history is reloaded. It is recommended that you should use separate working directories for analyses conducted with R. It is quite common for objects with names x and y to be created during an analysis.

Names like this are often meaningful in the context of a single analysis, but it can be quite hard to decide what they might be when the several analyses have been conducted in the same directory.



Recall and correction of previous commands
Under many versions of UNIX and on Windows, R provides a mechanism for recalling and reexecuting previous commands. The vertical arrow keys on the keyboard can be used to scroll forward and backward through a command history. Once a command is located in this way, the cursor can be moved within the command using the horizontal arrow keys, and characters can be removed with the DEL key or added with the other keys.

Executing commands from or diverting output to a file
If commands4 are stored in an external file, say ‘commands.R’ in the working directory ‘work’, they may be executed at any time in an R session with the command
> source("commands.R")
For Windows Source is also available on the File menu. The function sink,
> sink("record.lis")
will divert all subsequent output from the console to an external file, ‘record.lis’. The command
> sink()
restores it to the console once again.



Vectors and assignment
R operates on named data structures. The simplest such structure is the numeric vector, which is a single entity consisting of an ordered collection of numbers. To set up a vector named x, say, consisting of five numbers, namely 10.4, 5.6, 3.1, 6.4 and 21.7, use the R command
> x <- c(10.4, 5.6, 3.1, 6.4, 21.7)
This is an assignment statement using the function c() which in this context can take an arbitrary number of vector arguments and whose value is a vector got by concatenating its arguments end to end..
A number occurring by itself in an expression is taken as a vector of length one.
Notice that the assignment operator (‘<-’), which consists of the two characters ‘<’ (“less than”) and ‘-’ (“minus”) occurring strictly side-by-side and it ‘points’ to the object receiving the value of the expression. In most contexts the ‘=’ operator can be used as a alternative.

Assignment can also be made using the function assign(). An equivalent way of making the same assignment as above is with:
> assign("x", c(10.4, 5.6, 3.1, 6.4, 21.7))

The usual operator, <-, can be thought of as a syntactic short-cut to this.
Assignments can also be made in the other direction, using the obvious change in the assignment operator. So the same assignment could be made using
> c(10.4, 5.6, 3.1, 6.4, 21.7) -> x
If an expression is used as a complete command, the value is printed and lost2. So now if we were to use the command
> 1/x
the reciprocals of the five values would be printed at the terminal (and the value of x, of course, unchanged).
The further assignment
> y <- c(x, 0, x)
would create a vector y with 11 entries consisting of two copies of x with a zero in the middle place.

Vector arithmetic
Vectors can be used in arithmetic expressions, in which case the operations are performed element by element. Vectors occurring in the same expression need not all be of the same length. If they are not, the value of the expression is a vector with the same length as the longest vector which occurs in the expression. Shorter vectors in the expression are recycled as often as need be (perhaps fractionally) until they match the length of the longest vector. In particular a constant
is simply repeated. So with the above assignments the command
> v <- 2*x + y + 1
generates a new vector v of length 11 constructed by adding together, element by element, 2*x
repeated 2.2 times, y repeated just once, and 1 repeated 11 times.
The elementary arithmetic operators are the usual +, -, *, / and ^ for raising to a power. In addition all of the common arithmetic functions are available. log, exp, sin, cos, tan, sqrt, and so on, all have their usual meaning. max and min select the largest and smallest elements of a vector respectively. range is a function whose value is a vector of length two, namely c(min(x), max(x)). length(x) is the number of elements in x, sum(x) gives the total of the elements in x, and prod(x) their product.

Two statistical functions are mean(x) which calculates the sample mean, which is the same as sum(x)/length(x), and var(x) which gives sum((x-mean(x))^2)/(length(x)-1) or sample variance. If the argument to var() is an n-by-p matrix the value is a p-by-p sample covariance matrix got by regarding the rows as independent p-variate sample vectors. sort(x) returns a vector of the same size as x with the elements arranged in increasing order; however there are other more flexible sorting facilities available (see order() or sort.list() which produce a permutation to do the sorting).
Note that max and min select the largest and smallest values in their arguments, even if they are given several vectors. The parallel maximum and minimum functions pmax and pmin return a vector (of length equal to their longest argument) that contains in each element the largest (smallest) element in that position in any of the input vectors.

For most purposes the user will not be concerned if the “numbers” in a numeric vector are integers, reals or even complex. Internally calculations are done as double precision real numbers, or double precision complex numbers if the input data are complex.

To work with complex numbers, supply an explicit complex part. Thus
sqrt(-17)
will give NaN and a warning, but
sqrt(-17+0i)
will do the computations as complex numbers.


Generating regular sequences

R has a number of facilities for generating commonly used sequences of numbers. For example 1:30 is the vector c(1, 2, ..., 29, 30). The colon operator has high priority within an expression, so, for example 2*1:15 is the vector c(2, 4, ..., 28, 30). Put n <- 10 and compare the sequences 1:n-1 and 1:(n-1).

The construction 30:1 may be used to generate a sequence backwards.
The function seq() is a more general facility for generating sequences. It has five arguments, only some of which may be specified in any one call. The first two arguments, if given, specify the beginning and end of the sequence, and if these are the only two arguments given the result is the same as the colon operator. That is seq(2,10) is the same vector as 2:10.
Parameters to seq(), and to many other R functions, can also be given in named form, in which case the order in which they appear is irrelevant. The first two parameters may be named from=value and to=value; thus seq(1,30), seq(from=1, to=30) and seq(to=30, from=1) are all the same as 1:30. The next two parameters to seq() may be named by=value and length=value, which specify a step size and a length for the sequence respectively. If neither of these is given, the default by=1 is assumed.
For example
> seq(-5, 5, by=.2) -> s3
generates in s3 the vector c(-5.0, -4.8, -4.6, ..., 4.6, 4.8, 5.0). Similarly
> s4 <- seq(length=51, from=-5, by=.2)
generates the same vector in s4.

The fifth parameter may be named along=vector, which if used must be the only parameter, and creates a sequence 1, 2, ..., length(vector), or the empty sequence if the vector is empty (as it can be). A related function is rep() which can be used for replicating an object in various complicated
ways. The simplest form is
> s5 <- rep(x, times=5)
which will put five copies of x end-to-end in s5. Another useful version is
> s6 <- rep(x, each=5)
which repeats each element of x five times before moving on to the next.


Logical vectors
As well as numerical vectors, R allows manipulation of logical quantities. The elements of a logical vector can have the values TRUE, FALSE, and NA (for “not available”, see below). The first two are often abbreviated as T and F, respectively. Note however that T and F are just variables which are set to TRUE and FALSE by default, but are not reserved words and hence canbe overwritten by the user. Hence, you should always use TRUE and FALSE.
Logical vectors are generated by conditions. For example
> temp <- x > 13
sets temp as a vector of the same length as x with values FALSE corresponding to elements of x where the condition is not met and TRUE where it is.

The logical operators are <, <=, >, >=, == for exact equality and != for inequality. In addition if c1 and c2 are logical expressions, then c1 & c2 is their intersection (“and”), c1 | c2 is their union (“or”), and !c1 is the negation of c1. Logical vectors may be used in ordinary arithmetic, in which case they are coerced into numeric vectors, FALSE becoming 0 and TRUE becoming 1. However there are situations where logical vectors and their coerced numeric counterparts are not equivalent,


Character vectors
Character quantities and character vectors are used frequently in R, for example as plot labels. Where needed they are denoted by a sequence of characters delimited by the double quote character, e.g., "x-values", "New iteration results". Character strings are entered using either double (") or single (’) quotes, but are printed using double quotes (or sometimes without quotes). They use C-style escape sequences, using \ as the escape character, so \\ is entered and printed as \\, and inside double quotes " is entered as \". Other useful escape sequences are \n, newline, \t, tab and \b, backspace. Character vectors may be concatenated into a vector by the c() function; examples of their use will emerge frequently.


Objects their modes and attributes:


mode and length

The entities R operates on are technically known as objects. Examples are vectors of numeric (real) or complex values, vectors of logical values and vectors of character strings. These are known as “atomic” structures since their components are all of the same type, or mode, namely numeric1, complex, logical, character and raw.

Vectors must have their values all of the same mode. Thus any given vector must be unambiguously either logical, numeric, complex, character or raw. (The only apparent exception to this rule is the special “value” listed as NA for quantities not available, but in fact there are several types of NA). Note that a vector can be empty and still have a mode. For example the empty character string vector is listed as character(0) and the empty numeric vector as numeric(0).

R also operates on objects called lists, which are of mode list. These are ordered sequences of objects which individually can be of any mode. lists are known as “recursive” rather than atomic structures since their components can themselves be lists in their own right. The other recursive structures are those of mode function and expression. Functions are the objects that form part of the R system along with similar user written functions. Expressions as objects form an advanced part of R which will be explained in formulae used with modeling in R.

By the mode of an object we mean the basic type of its fundamental constituents. This is a special case of a “property” of an object. Another property of every object is its length. The functions mode(object) and length(object) can be used to find out the mode and length of any defined structure2.
Further properties of an object are usually provided by attributes(object). Because of this, mode and length are also called “intrinsic attributes” of an object.
For example, if z is a complex vector of length 100, then in an expression mode(z) is the character string "complex" and length(z) is 100.

R caters for changes of mode almost anywhere it could be considered sensible to do so, (and a few where it might not be). For example with
> z <- 0:9
we could put
> digits <- as.character(z)

after which digits is the character vector c("0", "1", "2", ..., "9"). A further coercion, or change of mode, reconstructs the numerical vector again:
> d <- as.integer(digits)

Now d and z are the same.3 There is a large collection of functions of the form as.something() for either coercion from one mode to another, or for investing an object with some other attribute it may not already possess.

Changing the length of an object
An “empty” object may still have a mode. For example
> e <- numeric()

makes e an empty vector structure of mode numeric. Similarly character () is a empty character vector, and so on. Once an object of any size has been created, new components may be added to it simply by giving it an index value outside its previous range. Thus
> e[3] <- 17

now makes e a vector of length 3, (the first two components of which are at this point both NA).
This applies to any structure at all, provided the mode of the additional component(s) agrees with the mode of the object in the first place.

This automatic adjustment of lengths of an object is used often, for example in the scan() function for input.

Conversely to truncate the size of an object requires only an assignment to do so. Hence if alpha is an object of length 10, then
> alpha <- alpha[2 * 1:5]

makes it an object of length 5 consisting of just the former components with even index. (The old indices are not retained, of course.) We can then retain just the first three values by
> length(alpha) <- 3

and vectors can be extended (by missing values) in the same way.






Source:
D. M. Smith, W. N. Venables, and the R Development Core Team, An Introduction to R, Notes on R: A Programming Environment for Data Analysis and Graphics Version 2.4.0 (2006-10-03)