NB: this is an Rstudio version of the document here: https://cran.r-project.org/doc/contrib/usingR.pdf Supporting code and data can be found here: https://github.com/dupadhyaya/usingR

1. Starting Up

R and R studio must must be installed on your system!

You should have a separate working directory for each major project. You can store data inputs and R outputs there

First create the directory in Explorer (PC) or Finder (Mac) and then navigate through the RStuio menu: Session > Set Working Directory > Choose Directory or if you are working from a script already in that directory Session > Set Working Directory > Tp Source File Location.

1.1 Getting started under Windows

This document mostly assumes that users will type commands into the command window, at the command line prompt.

The command line prompt, i.e. the > is an invitation to start typing in your commands. For example, type 2+2 and press the Enter key. Here is what appears on the screen:

2+2 
## [1] 4

Here the result is 4. The[1] says, a little strangely, first requested element will follow. Here, there is just one element. The > indicates that R is ready for another command.

1.2 Use of an Editor Script Window

You should always write your code in script than can be saved and re-run.

To open a new script file window File > New File > R Script

To load an existing file, File > Open File and then navigate to your file or of you have recenly ipened it File > Recent Files >

1.3 A Short R Session

We will read into R a file that holds population figures for Australian states and territories, and total population, at various times since 1917, then using this file to create a graph. First navigate to the file location where the data are saved and load the data into a R object called austpop

austpop <- read.table("austpop.txt", header=TRUE)

The <- is a left diamond bracket < followed by a minus sign -. It means is assigned to. Use of header=TRUE causes R to use the first line to get header information for the columns. If column headings The object austpop is, in R parlance, a data.frame. Data frames that consist entirely of numeric data have the same form of rectangular layout as numeric matrices. Have a look at the data

austpop
##   Year  NSW Vic.  Qld   SA   WA Tas.  NT ACT Aust.
## 1 1917 1904 1409  683  440  306  193   5   3  4941
## 2 1927 2402 1727  873  565  392  211   4   8  6182
## 3 1937 2693 1853  993  589  457  233   6  11  6836
## 4 1947 2985 2055 1106  646  502  257  11  17  7579
## 5 1957 3625 2656 1413  873  688  326  21  38  9640
## 6 1967 4295 3274 1700 1110  879  375  62 103 11799
## 7 1977 5002 3837 2130 1286 1204  415 104 214 14192
## 8 1987 5617 4210 2675 1393 1496  449 158 265 16264
## 9 1997 6274 4605 3401 1480 1798  474 187 310 18532

Below is a plot of the Australian Capital Territory (ACT) population between 1917 and 1997. We first of all remind ourselves of the column names:

names(austpop)
##  [1] "Year"  "NSW"   "Vic."  "Qld"   "SA"    "WA"    "Tas."  "NT"    "ACT"  
## [10] "Aust."

Plot the population of Australian Capital Territory, at various times between 1917 and 1997 The code to plot the graph is:

plot(ACT ~ Year, data=austpop, pch=16)

The option pch=16 sets the plotting character to a solid black dot. More plot characters are available - examine the help for points():

?points

This plot can be improved greatly. We can specify more informative axis labels, change size of the text and of the plotting symbol, and so on.

1.3.1 Entry of Data at the Command Line

A data frame is a rectangular array of columns of data. Here we will have two columns, and both columns will be numeric. The following data gives, for each amount by which an elastic band is stretched over the end of a ruler, the distance that the band moved when released.

elasticband <- data.frame(stretch=c(46,54,48,50,44,42,52),
                          distance=c(148,182,173,166,109,141,166))

The function data.frame() can be used to input these (or other) data directly at the command line.

1.3.2 Entry and/or editing of data in an editor window

To edit the data frame elasticband in a spreadsheet-like format,

elasticband <- edit(elasticband)

This opnes and Editor window, showing the data frame elasticband.

1.3.3 Options for read.table()

The function read.table() takes, optionally various parameters additional to the file name that holds the data. Specify header=TRUE if there is an initial row of header names. The default is header=FALSE. In addition users can specify the separator character or characters. Command alternatives to the default use of a space are sep="," and sep="\t". This last choice makes tabs separators. Similarly, users can control over the choice of missing value character or characters, which by default is NA.

There are several variants of read.table() that differ only in having different default parameter settings. Note in particular read.csv(), which has settings that are suitable for comma delimited (csv) files that have been generated from Excel spreadsheets.

If read.table() detects that lines in the input file have different numbers of fields, data input will fail, with an error message that draws attention to the discrepancy. It is then often useful to use the function count.fields() to report the number of fields that were identified on each separate line of the file.

1.4 Further Notational Details

As noted earlier, the command line prompt is
>
R commands (expressions) are typed following this prompt. There is also a continuation prompt, used when, following a carriage return, the command is still not complete. By default, the continuation prompt is +

In these notes, we often continue commands over more than one line, but omit the + that will appear on the commands window if the command is typed in as we show it.

For the names of R objects or commands, case is significant. Thus Austpop is different from austpop. For file names however, the Microsoft Windows conventions apply, and case does not distinguish file names. On Unix systems letters that have a different case are treated as different.

Anything that follows a # on the command line is taken as comment and ignored by R.

1.5 On-line Help

To get a help window (under R for Windows) with a list of help topics, type:

help()

An alternative is to click on the help menu item, and then use key words to do a search. To get help on a specific R function, e.g. plot(), type in

help(plot)

or

?(plot)

The two search functions help.search() and apropos() can be a huge help in finding what one wants. Examples of their use are:

help.search("matrix")

This lists all functions whose help pages have a title or alias in which the text string matrix appears.

apropos(_matrix_)

This lists all function names that include the text matrix.

The function help.start() opens a browser window that gives access to the full range of documentation for syntax, packages and functions. Experimentation often helps clarify the precise action of an R function.

1.6 The Loading or Attaching of Datasets

The recommended way to access datasets that are supplied for use with these notes is to attach the file using the usingR.RData file. This should have been downloaded and placed in the working directory and, from within the R session, type:

attach("usingR.RData")
## The following objects are masked _by_ .GlobalEnv:
## 
##     austpop, elasticband

Note the message: this is because the R objects austpop and elasticband were already in the R session (you crested them using the code above). These are now masked by the objects with the same name that were loaded with usingR.RData.

Users can also load (use load()) or attach (use attach()) specific files. These have a similar effect, the difference being that with attach() datasets are loaded into memory only when required for use. Distinguish between the attaching of image files and the attaching of data frames. The attaching of data frames will be discussed later in these notes.

1.7 Exercises

  1. In the data frame elasticband from section 1.3.1, plot distance against stretch.

  2. The following ten observations, taken during the years 1970-79, are on October snow cover for Eurasia. (Snow cover is in millions of square kilometers):

##    year snow.cover
## 1  1970        6.5
## 2  1971       12.0
## 3  1972       14.9
## 4  1973       10.0
## 5  1974       10.7
## 6  1975        7.9
## 7  1976       21.9
## 8  1977       12.5
## 9  1978       14.5
## 10 1979        9.2
  1. Enter the data into R. (Section 1.3.1 showed one way to do this. To save keystrokes, enter the successive years as 1970:1979.
  2. Plot snow.cover versus year. iii Use the hist() command to plot a histogram of the snow cover values.
  3. Repeat ii and iii after taking logarithms of snow cover using the log() function.

2. An Overview of R

2.1 The Uses of R

2.1.1 R may be used as a calculator.

R evaluates and prints out the result of any expression that one types in at the command line in the console window. Expressions are typed following the prompt > on the screen. The result, if any, appears on subsequent lines

2+2
sqrt(10)
2*3*4*5
1000*(1+0.075)^5 - 1000 # Interest on $1000, compounded annually
# at 7.5% p.a. for five years
pi # R knows about pi
2*pi*6378 #Circumference of Earth at Equator, in km; radius is 6378 km 
sin(c(30,60,90)*pi/180) # Convert angles to radians, then take sin() 

2.1.2 R will provide numerical or graphical summaries of data

A special class of object, called a data.frame, stores rectangular arrays in which the columns may be vectors of numbers or factors or text strings. Data frames are central to the way that all the more recent R routines process data. For now, think of data frames as matrices, where the rows are observations and the columns are variables. First load some data. The code below loads 5 datasets for use in this worksheet additional to any already present:

load("Maind_lex.RData") # Assumes Maind_lex.Rdata is in the working directory 
ls()
## [1] "austpop"        "Cars93.summary" "elasticband"    "florida"       
## [5] "hills"          "primates"       "rainforest"     "snow.cover"    
## [9] "year"

Note you could clear the workspace and re-run the 2 lines of code above in 2 ways: Session > Clear Workspace Or by entering { eval = F} rm(list=ls())

As a first example, consider the data frame hills. This has three columns (variables), with the names distance, climb, and time. Typing in summary(hills) gives summary information on these variables. There is one column for each variable, thus:

summary(hills)
##     distance          climb           time       
##  Min.   : 2.000   Min.   : 300   Min.   : 15.95  
##  1st Qu.: 4.500   1st Qu.: 725   1st Qu.: 28.00  
##  Median : 6.000   Median :1000   Median : 39.75  
##  Mean   : 7.529   Mean   :1815   Mean   : 57.88  
##  3rd Qu.: 8.000   3rd Qu.:2200   3rd Qu.: 68.62  
##  Max.   :28.000   Max.   :7500   Max.   :204.62

We may for example require information on ranges of variables. Thus the range of distances (first column) is from 2 miles to 28 miles, while the range of times (third column) is from 15.95 (minutes) to 204.6 minutes. We will discuss graphical summaries in the next section.

2.1.3 R has extensive graphical abilities

The main R graphics function is plot(). In addition to plot() there are functions for adding points and lines to existing graphs, for placing text at specified positions, for specifying tick marks and tick labels, for labelling axes, and so on. There are various other alternative helpful forms of graphical summary. A helpful graphical summary for the hills data frame is the scatterplot matrix, shown in Figure 5. For this, type:

pairs(hills)

to plot the Scatterplot matrix for the Scottish hill race data

2.1.4 R will handle a variety of specific analyses

The examples that will be given are correlation and regression. Correlation: We calculate the correlation matrix for the hills data:

cor(hills)
##           distance     climb      time
## distance 1.0000000 0.6523461 0.9195892
## climb    0.6523461 1.0000000 0.8052392
## time     0.9195892 0.8052392 1.0000000

or to just round to 3 decimal places

round(cor(hills), 3)
##          distance climb  time
## distance    1.000 0.652 0.920
## climb       0.652 1.000 0.805
## time        0.920 0.805 1.000

Suppose we wish to calculate logarithms, and then calculate correlations. We can do all this in one step, thus:

cor(log(hills))
##           distance     climb      time
## distance 1.0000000 0.7001366 0.8901429
## climb    0.7001366 1.0000000 0.7235184
## time     0.8901429 0.7235184 1.0000000

Unfortunately R was not clever enough to relabel distance as log(distance), climb as log(climb), and time as log(time). Notice that the correlations between time and distance, and between time and climb, have reduced. Why has this happened?

Straight Line Regression:

Here is a straight line regression calculation. The data are stored in the data frame elasticband. The variable names are the names of columns in that data frame. The formula that is supplied to the lm() command asks for the regression of distance travelled by the elastic band (distance) on the amount by which it is stretched (stretch).

plot(distance ~ stretch,data=elasticband, pch=16)

elastic.lm <- lm(distance~stretch,data=elasticband) 
lm(distance ~stretch,data=elasticband)
## 
## Call:
## lm(formula = distance ~ stretch, data = elasticband)
## 
## Coefficients:
## (Intercept)      stretch  
##     -63.571        4.554

More complete information is available by typing

summary(lm(distance~stretch,data=elasticband)) 
## 
## Call:
## lm(formula = distance ~ stretch, data = elasticband)
## 
## Residuals:
##        1        2        3        4        5        6        7 
##   2.1071  -0.3214  18.0000   1.8929 -27.7857  13.3214  -7.2143 
## 
## Coefficients:
##             Estimate Std. Error t value Pr(>|t|)  
## (Intercept)  -63.571     74.332  -0.855   0.4315  
## stretch        4.554      1.543   2.951   0.0319 *
## ---
## Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
## 
## Residual standard error: 16.33 on 5 degrees of freedom
## Multiple R-squared:  0.6352, Adjusted R-squared:  0.5622 
## F-statistic: 8.706 on 1 and 5 DF,  p-value: 0.03186

2.1.5 R is an Interactive Programming Language

We calculate the Fahrenheit temperatures that correspond to Celsius temperatures 25, 26, …, 30:

celsius <- 25:30
fahrenheit <- 9/5*celsius+32
conversion <- data.frame(Celsius=celsius, Fahrenheit=fahrenheit) 
print(conversion)
##   Celsius Fahrenheit
## 1      25       77.0
## 2      26       78.8
## 3      27       80.6
## 4      28       82.4
## 5      29       84.2
## 6      30       86.0

2.2 R Objects

All R entities, including functions and data structures, exist as objects. They can all be operated on as data. Type in ls() to see the names of all objects in your workspace. An alternative to ls() is objects(). In both cases there is provision to specify a particular pattern, e.g. starting with the letter p

It is also possible to save individual objects, or collections of objects into a named image file. Some possibilities are:

save.image() # Save contents of workspace, into the file .RData 
save.image(file="archive.RData") # Save into the file archive.RData 
save(celsius, fahrenheit, file="tempscales.RData")

Image files, from the working directory or (with the path specified) from another directory, can be attached, thus making objects in the file available on request. For example

attach("tempscales.RData")
## The following objects are masked _by_ .GlobalEnv:
## 
##     celsius, fahrenheit
ls(pos=2) # Check the contents of the file that has been attached
## [1] "celsius"    "fahrenheit"

The parameter pos gives the position on the search list. (The search list is discussed later in this chapter, in Section 2.9.) Important: On quitting, R offers the option of saving the workspace image, by default in the file .RData in the working directory. This allows the retention, for use in the next session in the same workspace, any objects that were created in the current session. Careful housekeeping may be needed to distinguish between objects that are to be kept and objects that will not be used again. Before typing quitting, use rm() to remove objects that are no longer required. Saving the workspace image will then save everything remains. The workspace image will be automatically loaded upon starting another session in that directory.

2.3 Looping

A simple example of a for loop is

for (i in 1:10) print(i)

Here is another example of a for loop, to do in a complicated way what we did very simply in section 2.1.5:

# Celsius to Fahrenheit
for (celsius in 25:30)
  print(c(celsius, 9/5*celsius + 32))
## [1] 25 77
## [1] 26.0 78.8
## [1] 27.0 80.6
## [1] 28.0 82.4
## [1] 29.0 84.2
## [1] 30 86

2.3.1 More on looping

Here is a long-winded way to sum the three numbers 31, 51 and 91:

answer <- 0
for (j in c(31,51,91)){answer <- j+answer}
answer
## [1] 173

The calculation iteratively builds up the object answer, using the successive values of j listed in the vector c(31,51,91). i.e. Initially,j=31,and answer is assigned the value 31+0=31. Then j=51, and answer is assigned the value 51 + 31 = 82. Finally, j=91, and answer is assigned the value 91 + 81 = 173. Then the procedure ends, and the contents of answer can be examined by typing in answer and pressing the Enter key. There is a more straightforward way to do this calculation:

sum(c(31,51,91))
## [1] 173

Skilled R users have limited recourse to loops. There are often, as in this and earlier examples, better alternatives.

2.4 Vectors

Examples of vectors are

c(2,3,5,2,7,1)
3:10 # The numbers 3, 4, .., 10 
c(TRUE,FALSE,FALSE,FALSE,TRUE,TRUE,FALSE) 
c("Canberra","Sydney","Newcastle","Darwin")

Vectors may have mode logical, numeric or character. The first two vectors above are numeric, the third is logical (i.e. a vector with elements of mode logical), and the fourth is a string vector (i.e. a vector with elements of mode character).

The missing value symbol, which is NA, can be included as an element of a vector.

2.4.1 Joining (concatenating) vectors

The c in c(2, 3, 5, 7, 1) above is an acronym for concatenate, i.e. the meaning is: Join these numbers together in to a vector. Existing vectors may be included among the elements that are to be concatenated. In the following we form vectors x and y, which we then concatenate to form a vector z:

x <- c(2,3,5,2,7,1) 
x
## [1] 2 3 5 2 7 1
y <- c(10,15,12) 
y
## [1] 10 15 12
z <- c(x, y)
z
## [1]  2  3  5  2  7  1 10 15 12

The concatenate function c() may also be used to join lists.

2.4.2 Subsets of Vectors

There are two common ways to extract subsets of vectors. Note in both case the use of the square brackets [ ].

  1. Specify the numbers of the elements that are to be extracted, e.g.
x <- c(3,11,8,15,12)  # Assign to x the values 3, 11, 8, 15, 12
x[c(2,4)]   # Extract elements (rows) 2 and 4
## [1] 11 15

One can use negative numbers to omit elements:

x <- c(3,11,8,15,12)
x[-c(2,3)]
## [1]  3 15 12
  1. Specify a vector of logical values. The elements that are extracted are those for which the logical value is T. Thus suppose we want to extract values of x that are greater than 10.
x>10  # This generates a vector of logical (T or F)
## [1] FALSE  TRUE FALSE  TRUE  TRUE
x[x>10]
## [1] 11 15 12

Arithmetic relations that may be used in the extraction of subsets of vectors are < <= > >= == !=. The first four compare magnitudes, == tests for equality, and != tests for inequality.

2.4.3 The Use of NA in Vector Subscripts

Note that any arithmetic operation or relation that involves NA generates an NA. Set y as follows:

y <- c(1, NA, 3, 0, NA)

Bewarned that y[y==NA]<-0 leaves y unchanged. The reason is that all elements of y==NA evaluate to NA.This does not select an element of y, and there is no assignment. To replace all NAs by 0, use

y[is.na(y)] <- 0

2.4.4 Factors

A factor is stored internally as a numeric vector with values 1, 2, 3, k, where k is the number of levels. An attributes table gives the level for each integer value. Factors provide a compact way to store character strings. They are crucial in the representation of categorical effects in model and graphics formulae. The class attribute of a factor has, not surprisingly, the value factor.

Consider a survey that has data on 691 females and 692 males. If the first 691 are females and the next 692 males, we can create a vector of strings that that holds the values thus:

gender <- c(rep("female",691), rep("male",692))

The usage is that rep("female"", 691) creates 691 copies of the character string female, and similarly for the creation of 692 copies of male. We can change the vector to a factor, by entering:

gender <- factor(gender)

Internally the factor gender is stored as 691 1’s, followed by 692 2’s. It has stored with it the table: Once stored as a factor, the space required for storage is reduced.

In most cases where the context seems to demand a character string, the 1 is translated into female and the 2 into male. The values female and male are the levels of the factor. By default, the levels are in alphanumeric order, so that female precedes male. Hence:

levels(gender)  # Assumes gender is a factor, created as above
## [1] "female" "male"

The order of the levels in a factor determines the order in which the levels appear in graphs that use this information, and in tables. To cause male to come before female, use

gender <- relevel(gender, ref="male")

An alternative is

gender <- factor(gender, levels=c("male","female"))

This last syntax is available both when the factor is first created, or later when one wishes to change the order of levels in an existing factor. Incorrect spelling of the level names will generate an error message. Try

gender <- factor(c(rep("female",691), rep("male",692)))
table(gender)
## gender
## female   male 
##    691    692
gender <- factor(gender, levels=c("male","female"))
table(gender)
## gender
##   male female 
##    692    691
gender <- factor(gender, levels=c("Male", "female"))
table(gender)
## gender
##   Male female 
##      0    691
rm(gender) # Remove gender

The attributes() function makes it possible to inspect attributes. For example

attributes(factor(1:3))
## $levels
## [1] "1" "2" "3"
## 
## $class
## [1] "factor"

The function levels() gives a better way to inspect factor levels.

2.5 Data Frames

Data frames are fundamental to the use of the R modelling and graphics functions. A data frame is a generalisation of a matrix, in which different columns may have different modes. All elements of any column must however have the same mode, i.e. all numeric or all factor, or all character. Among the data sets loaded is Cars93.summary, created from information in the Cars93 data set in the Venables and Ripley MASS package. Here it is:

Cars93.summary
##         Min.passengers Max.passengers No.of.cars abbrev
## Compact              4              6         16      C
## Large                6              6         11      L
## Midsize              4              6         22      M
## Small                4              5         21     Sm
## Sporty               2              4         14     Sp
## Van                  7              8          9      V

The column names (access with names(Cars93.summary)) are Min.passengers (i.e. the minimum number of passengers for cars in this category), Max.passengers, No.of.cars., and abbrev. The first three columns have mode numeric, and the fourth has mode character. Columns can be vectors of any mode. The column abbrev could equally well be stored as a factor. Any of the following will pick out the fourth column of the data frame Cars93.summary, then store it in the vector type.

type <- Cars93.summary$abbrev
type <- Cars93.summary[,4]
type <- Cars93.summary[,"abbrev"]
type <- Cars93.summary[[4]]   # in the fourth list element.

2.5.1 Data frames as lists

A data frame is a list of column vectors, all of equal length. Just as with any other list, subscripting extracts a list. Thus Cars93.summary[4] is a data frame with a single column, which is the fourth column vector of Cars93.summary. As noted above, the are different ways of extracting a column vector. The use of matrix-like subscripting, e.g. Cars93.summary[,4] or Cars93.summary[1, 4], takes advantage of the rectangular structure of data frames.

2.5.2 Inclusion of character string vectors in data frames

When data are input using read.table(), or when the data.frame() function is used to create data frames, vectors of character strings are by default turned into factors. The parameter setting stringsAsFactors=TRUE, available both with read.table() and with data.frame(), will if needed ensure that character strings are input without such conversion. For read.table(), an alternative is as.is=TRUE.

2.5.3 Built-in data sets

We will often use data sets that accompany one of the R packages, usually stored as data frames. One such data frame, in the datasets package, is trees, which gives girth, height and volume for 31 Black Cherry Trees. Here is summary information on this data frame

summary(trees)
##      Girth           Height       Volume     
##  Min.   : 8.30   Min.   :63   Min.   :10.20  
##  1st Qu.:11.05   1st Qu.:72   1st Qu.:19.40  
##  Median :12.90   Median :76   Median :24.20  
##  Mean   :13.25   Mean   :76   Mean   :30.17  
##  3rd Qu.:15.25   3rd Qu.:80   3rd Qu.:37.30  
##  Max.   :20.60   Max.   :87   Max.   :77.00

Type data() to get a list of built-in data sets in the packages that have been attached

2.6 Common Useful Functions

print() # Prints a single R object
cat() # Prints multiple objects, one after the other 
length() # Number of elements in a vector or of a list
mean()
median()
range()
unique() # Gives the vector of distinct values
diff() # Replace a vector by the vector of first differences
# N. B. diff(x) has one less element than x 
sort() # Sort elements into order, but omitting NAs 
order() # x[order(x)] orders elements of x, with NAs last 
cumsum()
cumprod()
rev() # reverse the order of vector elements

The functions mean(), median(), range(), and a number of other functions, take the argument na.rm=T; i.e. remove NAs, then proceed with the calculation. By default, sort() omits any NAs. The function order() places NAs last. Hence:

x <- c(1, 20, 2, NA, 22)
order(x)
## [1] 1 3 2 5 4
x[order(x)]
## [1]  1  2 20 22 NA

2.6.1 Applying a function to all columns of a data frame

The function sapply() takes as arguments the the data frame, and the function that is to be applied. The following applies the function is.factor() to all columns of the supplied data frame rainforest.

sapply(rainforest, is.factor)
##     dbh    wood    bark    root  rootsk  branch species 
##   FALSE   FALSE   FALSE   FALSE   FALSE   FALSE    TRUE
sapply(rainforest[,-7], range)   # The final column (7) is a factor
##      dbh wood bark root rootsk branch
## [1,]   4   NA   NA   NA     NA     NA
## [2,]  56   NA   NA   NA     NA     NA

One can specify na.rm=TRUE as a third argument to the function sapply(). This argument is then automatically passed to the function that is specified in the second argument position. For example:

sapply(rainforest[,-7], range, na.rm=TRUE) 
##      dbh wood bark root rootsk branch
## [1,]   4    3    8    2    0.3      4
## [2,]  56 1530  105  135   24.0    120

2.7 Making Tables

table() makes a table of counts. Specify one vector of values (often a factor) for each table margin that is required. For example install the lattice package as below :

install.packages("lattice", dep = T)

Then it can be called

library(lattice) 
# The data frame barley accompanies lattice 
table(barley$year, barley$site)
##       
##        Grand Rapids Duluth University Farm Morris Crookston Waseca
##   1932           10     10              10     10        10     10
##   1931           10     10              10     10        10     10

WARNING: NAs are by default ignored. The action needed to get NAs tabulated under a separate NA category depends, annoyingly, on whether or not the vector is a factor. If the vector is not a factor, specify exclude=NULL. If the vector is a factor then it is necessary to generate a new factor that includes NA as a level. Specify x <- factor(x,exclude=NULL)

x <- c(1,5,NA,8) 
x <- factor(x) 
x
## [1] 1    5    <NA> 8   
## Levels: 1 5 8
factor(x,exclude=NULL)
## [1] 1    5    <NA> 8   
## Levels: 1 5 8 <NA>

2.7.1 Numbers of NAs in subgroups of the data

The following gives information on the number of NAs in subgroups of the data:

table(rainforest$species, !is.na(rainforest$branch))
##                  
##                   FALSE TRUE
##   Acacia mabellae     6   10
##   C. fraseri          0   12
##   Acmena smithii     15   11
##   B. myrtifolia       1   10

Thus for Acacia mabellae there are 6 NAs for the variable branch (i.e. number of branches over 2cm in diameter), out of a total of 16 data values.

2.8 The Search List

R has a search list where it looks for objects. This can be changed in the course of a session. To get a full list of these directories, called databases, type:

search()
##  [1] ".GlobalEnv"            "package:lattice"       "file:tempscales.RData"
##  [4] "file:usingR.RData"     "package:stats"         "package:graphics"     
##  [7] "package:grDevices"     "package:utils"         "package:datasets"     
## [10] "package:methods"       "Autoloads"             "package:base"

Notice that the loading of a new package extends the search list. First install the package if you have not used it before.

install.packages("MASS", dep = T)

Then call it

library(MASS)
## 
## Attaching package: 'MASS'
## The following object is masked _by_ '.GlobalEnv':
## 
##     hills
search()
##  [1] ".GlobalEnv"            "package:MASS"          "package:lattice"      
##  [4] "file:tempscales.RData" "file:usingR.RData"     "package:stats"        
##  [7] "package:graphics"      "package:grDevices"     "package:utils"        
## [10] "package:datasets"      "package:methods"       "Autoloads"            
## [13] "package:base"

The use of attach() likewise extends the search list. This function can be used to attach data frames or lists (use the name, without quotes) or image (.RData) files (the file name is placed in quotes). The following demonstrates the attaching of the data frame primates:

names(primates)
## [1] "Bodywt"  "Brainwt"
Bodywt
Error: object 'Bodywt' not found

Once the data frame primates has been attached, its columns can be accessed by giving their names, without further reference to the name of the data frame. In technical terms, the data frame becomes a database, which is searched as required for objects that the user may specify. Remember to detach an attached data frame, e.g., detach(primates), when it is no longer required. Note also the function with(), which attaches the data frame that is given as its first argument for the duration of the calculation that is specified by its second argument. For example:

av <- with(primates, mean(Bodywt))

2.9 Functions in R

We give two simple examples of R functions.

2.9.1 An Approximate Miles to Kilometers Conversion

miles.to.km <- function(miles)miles*8/5

The return value is the value of the final (and in this instance only) expression that appears in the function body18. Use the function thus

miles.to.km(175) # Approximate distance to Sydney, in miles [1] 280
## [1] 280

The function will do the conversion for several distances all at once. To convert a vector of the three distances 100, 200 and 300 miles to distances in kilometers, specify:

miles.to.km(c(100,200,300))
## [1] 160 320 480

2.9.2 A Plotting function

The data set florida has the votes in the 2000 election for the various US Presidential candidates, county by county in the state of Florida. The following plots the vote for Buchanan against the vote for Bush.

attach(florida)
plot(BUSH, BUCHANAN, xlab="Bush", ylab="Buchanan") 

detach(florida) #

Here is a function that makes it possible to plot the figures for any pair of candidates.

plot.florida <- function(xvar="BUSH", yvar="BUCHANAN"){
  x <- florida[,xvar]
  y <- florida[,yvar]
  plot(x, y, xlab=xvar,ylab=yvar)
  mtext(side=3, line=1.75, "Votes in Florida, by county, in \nthe 2000 US Presidential election")
}

Note that the function body is enclosed in braces ({ }). The plot shows the graph produced by plot.florida(), i.e. parameter settings are left at their defaults, with the election night count of votes received, by county, in the US 2000 Presidential election.

As well as plot.florida(), the function allows, e.g.

plot.florida(yvar="NADER") # yvar="NADER"" over-rides the default 

plot.florida(xvar="GORE", yvar="NADER")