Search for notes by fellow students, in your own course and all over the country.

Browse our notes for titles which look like what you need, you can preview any of the notes via a sample of the contents. After you're happy these are the notes you're after simply pop them into your shopping cart.

My Basket

You have nothing in your shopping cart yet.

Title: R for beginners
Description: just to know the basic of R(Big Data)

Document Preview

Extracts from the notes are below, to see the PDF you'll receive please use the links above


R for Beginners
Emmanuel Paradis

´
Institut des Sciences de l’Evolution
Universit´ Montpellier II
e
F-34095 Montpellier c´dex 05
e
France
E-mail: paradis@isem
...
fr

´
I thank Julien Claude, Christophe Declercq, Elodie Gazave, Friedrich Leisch,
Louis Luangkesron, Fran¸ois Pinard, and Mathieu Ros for their comments and
c
suggestions on earlier versions of this document
...
Thanks also to the
R users whose questions or comments helped me to write “R for Beginners”
...


c 2002, 2005, Emmanuel Paradis (12th September 2005)
Permission is granted to make and distribute copies, either in part or in
full and in any language, of this document on any support provided the above
copyright notice is included in all copies
...


Contents

1 Preamble

1

2 A few concepts before starting
2
...

2
...

2
...


3
3
5
7

3 Data with R
3
...

3
...

3
...

3
...

3
...
1 Regular sequences
...
4
...

3
...

3
...
1 Creating objects
...
5
...

3
...
3 Operators
...
5
...
5
...

3
...
6 The data editor
...
5
...

3
...
8 Matrix computation
...


...


...


...


...


...


...


...


9
9
11
14
15
15
17
18
18
23
25
26
29
31
31
33

4 Graphics with R
4
...

4
...
1 Opening several graphical devices
4
...
2 Partitioning a graphic
...
2 Graphical functions
...
3 Low-level plotting commands
...
4 Graphical parameters
...
5 A practical example
...
6 The grid and lattice packages
...


...


...


...


...


...


...


...


...


...


...


...


...


...


...


...


...


...


...


...


...


...


...


...


...


...


...


...


...


...


...


...


...


...


...


...


...


...


...


...


...


...


...


...


...


...


...


...


...


...


...


...


...
1 A simple example of analysis of variance
5
...

5
...

5
...



...


...



...


...



...


...



...


...



...


...



...


...



...


...



...


...



...


...



...


...



...


...



...


...



...


...


55
55
56
58
61

6 Programming with R in pratice
6
...

6
...

6
...


64
64
66
67

7 Literature on R

71

1

Preamble

The goal of the present document is to give a starting point for people newly
interested in R
...
Given that the possibilities
offered by R are vast, it is useful to a beginner to get some notions and
concepts in order to progress easily
...

R is a system for statistical analyses and graphics created by Ross Ihaka
and Robert Gentleman1
...
S is available
as the software S-PLUS commercialized by Insightful 2
...

R is freely distributed under the terms of the GNU General Public Licence 4 ;
its development and distribution are carried out by several statisticians known
as the R Development Core Team
...
The files needed
to install R, either from the sources or from the pre-compiled binaries, are
distributed from the internet site of the Comprehensive R Archive Network
(CRAN)5 where the instructions for the installation are also available
...
), the binaries are generally
available for the most recent versions; look at the CRAN site if necessary
...
The results from a statistical analysis are
displayed on the screen, some intermediate results (P-values, regression coefficients, residuals,
...

The R language allows the user, for instance, to program loops to successively analyse several data sets
...
The
1

Ihaka R
...
1996
...
Journal
of Computational and Graphical Statistics 5: 299–314
...
insightful
...
asp for more information
3
http://cran
...
org/doc/FAQ/R-FAQ
...
gnu
...
r-project
...

At first, R could seem too complex for a non-specialist
...
In fact, a prominent feature of R is its flexibility
...
The user may be surprised by this, but such a feature is very useful
...

For example, if one runs a series of 20 regressions and wants to compare the
different regression coefficients, R can display only the estimated coefficients:
thus the results may take a single line, whereas a classical software could well
open 20 results windows
...


6

For example: http://stat
...
edu/S/

2

2

A few concepts before starting

Once R is installed on your computer, the software is executed by launching
the corresponding executable
...
Under Windows using the program Rgui
...
) can be executed
via the pull-down menus
...

We shall see first briefly how R works
...


2
...
This should not be the case for two reasons
...

Second, R’s syntax is very simple and intuitive
...
In R, in order to
be executed, a function always needs to be written with parentheses, even
if there is nothing within them (e
...
, ls())
...
In this
document, the names of the functions are generally written with parentheses in
order to distinguish them from other objects, unless the text indicates clearly
so
...

The user can do actions on these objects with operators (arithmetic, logical,
comparison,
...
The use of
operators is relatively intuitive, we will see the details later (p
...
An R
function may be sketched as follows:
arguments −→
options −→

function

default arguments

=⇒result

The arguments can be objects (“data”, formulae, expressions,
...
An R function may require no
argument: either all arguments are defined by default (and their values can be
modified with the options), or no argument has been defined in the function
...
67)
...

All the actions of R are done on objects stored in the active memory of
the computer: no temporary files are used (Fig
...
The readings and writings
of files are used for input and output of data and results (graphics,
...
The results are displayed
directly on the screen, stored in an object, or written on the disk (particularly
for graphics)
...
Data files can be read from the local disk or
from a remote server through internet
...
/library/base/
/stast/
/graphics/

...


Hard disk

Figure 1: A schematic view of how R works
...
This directory contains packages of functions, which are
themselves structured in directories
...
Each package has a directory called R with
a file named like the package (for instance, for the package base, this is the
file R HOME/library/base/R/base)
...

One of the simplest commands is to type the name of an object to display
its content
...
This command is an implicit use of the function print and the
above example is similar to print(n) (in some situations, the function print
must be used explicitly, such as within a function or a loop)
...
), and underscores ( )
...


2
...
The
value assigned this way may be the result of an operation and/or a function:
> n
> n
[1]
> n
> n
[1]

<- 10 + 2
12
<- 3 + rnorm(1)
2
...
17)
...

The function ls lists simply the objects in memory: only the names of the
objects are displayed
...
5
> ls()
[1] "m"
"n1"
"n2"
"name"
Note the use of the semi-colon to separate distinct commands on the same
line
...
str displays some details on the objects in memory:
> ls
...
5
n1 : num 10
n2 : num 100
name : chr "Carmen"
The option pattern can be used in the same way as with ls
...
str is max
...
By default, ls
...
We can avoid to display all these
details with the option max
...
frame(n1, n2, m)
> ls
...
frame’:
1 obs
...
5
> ls
...
level=-1)
M : ‘data
...
of

3 variables:

3 variables:

To delete objects in memory, we use the function rm: rm(x) deletes the
object x, rm(x,y) deletes both the objects x et y, rm(list=ls()) deletes all
the objects in memory; the same options mentioned for the function ls() can
then be used to delete selectively some objects: rm(list=ls(pat="^m"))
...
3

The on-line help

The on-line help of R gives very useful information on how to use the functions
...
The
commands help(lm) and help("lm") have the same effect
...

Calling help opens a page (this depends on the operating system) with
general information on the first line such as the name of the package where
is (are) the documented function(s) or operators
...

Description: brief description
...

Arguments: for a function, details each of its arguments
...

Value: if applicable, the type of object returned by the function or the operator
...

Examples: some examples which can generally be executed without opening
the help with the function example
...
Generally, it
is useful to read carefully the section Arguments
...

By default, the function help only searches in the packages which are
loaded in memory
...
all
...
search("bs")’
> help("bs", try
...
packages = TRUE)
Help for topic ’bs’ is not in any loaded package but
can be found in the following packages:
Package
splines

Library
/usr/lib/R/library

Note that in this case the help page of the function bs is not displayed
...


...
g
...
start()
A search with keywords is possible with this html help
...
The search with
keywords is also possible in R with the function help
...
The latter
looks for a specified topic, given as a character string, in the help pages of all
installed packages
...
search("tree") will display a list of
the functions which help pages mention “tree”
...
search using the option rebuild (e
...
, help
...

The fonction apropos finds all functions which name contains the character
string given as argument; only the packages loaded in memory are searched:
> apropos(help)
[1] "help"
[4] "help
...
helpForCall" "help
...
1

Data with R

Objects

We have seen that R works with objects which are, of course, characterized by
their names and their content, but also by attributes which specify the kind of
data represented by an object
...

It is clear that the statistical analysis of this variable will not be the same in
both cases: with R, the attributes of the object give the necessary information
...

All objects have two intrinsic attributes: mode and length
...
Other modes exist
but they do not represent data, for instance function or expression
...
To display the mode and the length
of an object, one can use the functions mode and length, respectively:
> x <- 1
> mode(x)
[1] "numeric"
> length(x)
[1] 1
> A <- "Gomphotherium"; compar <- TRUE; z <- 1i
> mode(A); mode(compar); mode(z)
[1] "character"
[1] "logical"
[1] "complex"
Whatever the mode, missing data are represented by NA (not available)
...
1e23
> N
[1] 2
...

7

The mode complex will not be discussed in this document
...
It is possible
to include this latter character in the value if it follows a backslash \
...
table to write on the disk (p
...

> x <- "Double quotes \" delimitate R’s strings
...
"
> cat(x)
Double quotes " delimitate R’s strings
...

> x
[1] "Double quotes \" delimitate R’s strings
...

object

vector
factor
array
matrix
data frame
ts
list

modes

several modes
possible in the
same object?

numeric, character, complex or logical
numeric or character
numeric, character, complex or logical
numeric, character, complex or logical
numeric, character, complex or logical
numeric, character, complex or logical
numeric, character, complex, logical,
function, expression,
...
A factor is a
categorical variable
...
Note that the elements of an array
or of a matrix are all of the same mode
...
A ‘ts’ is a time series data set and so contains additional
attributes such as frequency and dates
...
For
other objects, other information is necessary and it is given by non-intrinsic
attributes
...
For example, a matrix with 2 lines and 2 columns
has for dim the pair of values [2, 2], but its length is 4
...
2

Reading data in a file

For reading and writing in files, R uses the working directory
...
It is necessary to give the path to a file if it is not in the working
directory
...
table (which has several variants, see below), scan and read
...
R
can also read files in other formats (Excel, SAS, SPSS,
...

These functionalities are very useful for a more advanced use of R, but we will
restrict here to reading files in ASCII format
...
table has for effect to create a data frame, and so is
the main way to read data in tabular form
...
dat, the command:
> mydata <- read
...
dat")
will create a data frame named mydata, and each variable will be named, by default, V1, V2,
...
, or by mydata["V1"], mydata["V2"],
...
9 There are several options whose default
values (i
...
those used by R if they are omitted by the user) are detailed in
the following table:
read
...
",
8

Under Windows, it is useful to create a short-cut of Rgui
...

9
There is a difference: mydata$V1 and mydata[, 1] are vectors whereas mydata["V1"] is
a data frame
...
18) some details on manipulating objects
...
names, col
...
is = FALSE, na
...
names = TRUE, fill = !blank
...
skip,
strip
...
lines
...
char = "#")

file

header
sep
quote
dec
row
...
names
as
...
strings
colClasses
nrows
skip
check
...
white
blank
...
skip
comment
...
)
a logical (FALSE or TRUE) indicating if the file contains the names of
the variables on its first line
the field separator used in the file, for instance sep="\t" if it is a
tabulation
the characters used to cite the variables of mode character
the character used for the decimal point
a vector with the names of the lines which can be either a vector of
mode character, or the number (or the name) of a variable of the
file (by default: 1, 2, 3,
...
)
controls the conversion of character variables as factors (if FALSE)
or keeps them as characters (TRUE); as
...
char = "")

The variants of read
...
csv(file, header = TRUE, sep = ",", quote="\"", dec="
...
)
read
...
)
read
...
",
fill = TRUE,
...
delim2(file, header = TRUE, sep = "\t", quote="\"", dec=",",
fill = TRUE,
...
table
...
dat", what = list("", 0, 0))
reads in the file data
...
Another important distinction is that scan()
can be used to create different objects, vectors, matrices, data frames, lists,

...
By default, that is
if what is omitted, scan() creates a numeric vector
...
The options are the followings
...
",
skip = 0, nlines = 0, na
...
white = FALSE, quiet = FALSE,
blank
...
skip = TRUE, multi
...
char = "",
allowEscapes = TRUE)

file

what
nmax
n
sep
quote
dec
skip
nlines
na
...
white
quiet
blank
...
skip
multi
...
char
allowEscapes

the name of the file (within ""), possibly with its path (the symbol
\ is not allowed and must be replaced by /, even under Windows),
or a remote access to a file of type URL (http://
...
g
...
fwf can be used to read in a file some data in fixed
width format:
read
...
is = FALSE, skip = 0, row
...
names,
n = -1, buffersize = 2000,
...
table() except widths which specifies the width of the fields
(buffersize is the maximum number of lines read simultaneously)
...
txt has
the data indicated on the right, one can read the data
with the following command:

A1
...
2
A1
...
3
B1
...
4
B1
...
5
C1
...
6
C1
...
7

> mydata <- read
...
txt", widths=c(1, 4, 3))
> mydata
V1
V2 V3
1 A 1
...
2
2 A 1
...
3
3 B 1
...
4
4 B 1
...
5
5 C 1
...
6
6 C 1
...
7

3
...
table writes in a file an object, typically a data frame but
this could well be another kind of object (vector, matrix,
...
table(x, file = "", append = FALSE, quote = TRUE, sep = " ",
eol = "\n", na = "NA", dec = "
...
names = TRUE,
col
...
names
col
...
for the names of the columns
specifies, if quote=TRUE, how double quotes " included in variables of mode
character are treated: if "escape" (or "e", the default) each " is replaced
by \", if "d" each " is replaced by ""

14

To write in a simpler way an object in a file, the command write(x,
file="data
...
There are two options: nc (or ncol)
which defines the number of columns in the file (by default nc=1 if x is of mode
character, nc=5 for the other modes), and append (a logical) to add the data
without deleting those possibly already in the file (TRUE) or deleting them if
the file already exists (FALSE, the default)
...
RData")
...
The data (which are
now called a workspace in R’s jargon) can be loaded later in memory with
load("xyz
...
The function save
...
RData")
...
4

Generating data

3
...
1

Regular sequences

A regular sequence of integers, for example from 1 to 30, can be generated
with:
> x <- 1:30
The resulting vector x has 30 elements
...
5)
[1] 1
...
5 2
...
5 3
...
5 4
...
5 5
...

One can use also:
> seq(length=9, from=1, to=5)
[1] 1
...
5 2
...
5 3
...
5 4
...
5 5
...
5, 2, 2
...
5, 4, 4
...
0 1
...
0 2
...
0 3
...
0 4
...
0
15

It is also possible, if one wants to enter some data on the keyboard, to use
the function scan with simply the default options:
> z <- scan()
1: 1
...
5 2
...
5 3
...
5 4
...
5 5
...
0 1
...
0 2
...
0 3
...
0 4
...
0
The function rep creates a vector with all its elements identical:
> rep(1, 30)
[1] 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1
The function sequence creates a series of sequences of integers each ending
by the numbers given as arguments:
> sequence(4:5)
[1] 1 2 3 4 1 2 3 4 5
> sequence(c(10,5))
[1] 1 2 3 4 5 6

7

8

9 10

1

2

3

4

5

The function gl (generate levels) is very useful because it generates regular
series of factors
...
Two
options may be used: length to specify the number of data produced, and
labels to specify the names of the levels of the factor
...
grid() creates a data frame with all combinations of vectors or factors given as arguments:
> expand
...
4
...
These functions are
of the form rfunc (n, p1, p2,
...
are the values of
the parameters of the distribution
...

Most of these functions have counterparts obtained by replacing the letter
r with d, p or q to get, respectively, the probability density (dfunc (x,
...
)), and the value of quantile
(qfunc (p,
...
The last two series of functions can be
used to find critical values or P -values of statistical tests
...
025)
[1] -1
...
975)
[1] 1
...
05) or 1 qnorm(0
...

The P -value of a test, say χ2 = 3
...
84, 1)
[1] 0
...
5
3
...
1

Manipulating objects
Creating objects

We have seen previously different ways to create objects using the assign operator; the mode and the type of objects so created are generally determined
implicitly
...
This approach is interesting in the perspective of manipulating objects
...
The indexing system could be used here, as we will see later
(p
...

It can also be very convenient to create objects from others
...

At this stage of our learning of R, the interest in learning the following
functionalities is not only practical but also didactic
...

Vector
...
The following functions have exactly the same effect and have for
single argument the length of the vector: numeric(), logical(), and
character()
...
A factor includes not only the values of the corresponding categorical
variable, but also the different possible levels of that variable (even if they
are not present in the data)
...
last = TRUE),
labels = levels, exclude = NA, ordered = is
...
Recall
that x is of mode numeric or character
...

> factor(1:3)
[1] 1 2 3
Levels: 1 2 3
> factor(1:3, levels=1:5)
[1] 1 2 3
Levels: 1 2 3 4 5
> factor(1:3, labels=c("A", "B", "C"))
[1] A B C
Levels: A B C
> factor(1:5, exclude=4)
[1] 1 2 3 NA 5
Levels: 1 2 3 5
The function levels extracts the possible levels of a factor:
> ff <- factor(c(2, 4), levels=2:5)
> ff
[1] 2 4
Levels: 2 3 4 5
> levels(ff)
[1] "2" "3" "4" "5"
Matrix
...
A matrix can be created with the
function matrix:
matrix(data = NA, nrow = 1, ncol = 1, byrow = FALSE,
dimnames = NULL)

19

The option byrow indicates whether the values given by data must fill
successively the columns (the default) or the rows (if TRUE)
...

> matrix(data=5, nr=2, nc=2)
[,1] [,2]
[1,]
5
5
[2,]
5
5
> matrix(1:6, 2, 3)
[,1] [,2] [,3]
[1,]
1
3
5
[2,]
2
4
6
> matrix(1:6, 2, 3, byrow=TRUE)
[,1] [,2] [,3]
[1,]
1
2
3
[2,]
4
5
6
Another way to create a matrix is to give the appropriate values to the
dim attribute (which is initially NULL):
> x <- 1:15
> x
[1] 1 2 3 4 5
> dim(x)
NULL
> dim(x) <- c(5, 3)
> x
[,1] [,2] [,3]
[1,]
1
6
11
[2,]
2
7
12
[3,]
3
8
13
[4,]
4
9
14
[5,]
5
10
15

6

7

8

9 10 11 12 13 14 15

Data frame
...
table; it is also possible to create a data frame with the
function data
...
The vectors so included in the data frame must
be of the same length, or if one of the them is shorter, it is “recycled” a
whole number of times:
> x <- 1:4; n <- 10; M <- c(10, 35); y <- 2:4
> data
...
frame(x, M)
x M
1 1 10
2 2 35
3 3 10
4 4 35
> data
...
frame(x, y) :
arguments imply differing number of rows: 4, 3
If a factor is included in a data frame, it must be of the same length than
the vector(s)
...
frame(A1=x, A2=n)
...
names which must be, of course, a vector of
mode character and of length equal to the number of lines of the data
frame
...

List
...

There is no constraint on the objects that can be included
...
frame(), the names of the objects are not taken by default;
taking the vectors x and y of the previous example:
> L1 <- list(x, y); L2 <- list(A=x, B=y)
> L1
[[1]]
[1] 1 2 3 4
[[2]]
[1] 2 3 4
> L2
$A
[1] 1 2 3 4
$B
[1] 2 3 4
> names(L1)
NULL
> names(L2)
[1] "A" "B"
Time-series
...
The options, with the default values,
are:
ts(data = NA, start = 1, end = numeric(0), frequency = 1,
deltat = 1, ts
...
eps"), class, names)

data
start
end
frequency
deltat

ts
...
1/12 for monthly data); only one of
frequency or deltat must be given
tolerance for the comparison of series
...
eps
class to give to the object; the default is "ts" for a single
series, and c("mts", "ts") for a multivariate series
a vector of mode character with the names of the individual series in the case of a multivariate series; by default
the names of the columns of data, or Series 1, Series
2,
...
The objects of mode expression have a fundamental role in R
...
All valid
commands are expressions
...
In many
circumstances, it is useful to construct an expression without evaluating
it: this is what the function expression is made for
...

> x <- 3; y <- 2
...
5749019
Expressions can be used, among other things, to include equations in
graphs (p
...
An expression can be created from a variable of mode
character
...
5
...
Such a conversion will be
done with a function of the type as
...
R (version 2
...
0) has, in the
23

packages base and utils, 98 of such functions, so we will not go in the deepest
details here
...
Genrally, conversion follows intuitive rules
...

Conversion to

Function

numeric

as
...
logical

character

Rules

as
...

"A",
...

FALSE →
TRUE →

0
1
1, 2,
...

"FALSE"
"TRUE"

There are functions to convert the types of objects (as
...
ts,
as
...
frame, as
...
These functions will affect attributes
other than the modes during the conversion
...
A situation frequently encountered is the conversion of factors into
numeric values
...
numeric(fac)
[1] 1 2
This makes sense when considering a factor of mode character:
> fac2 <- factor(c("Male", "Female"))
> fac2
[1] Male
Female
Levels: Female Male
> as
...

24

To convert a factor of mode numeric into a numeric vector but keeping the
levels as they are originally specified, one must first convert into character,
then into numeric
...
numeric(as
...
We have seen that read
...

3
...
3

Operators

We have seen previously that there are three main types of operators in R 10
...

Operators
Comparison

Arithmetic
+
*
/
^
%%
%/%

addition
subtraction
multiplication
division
power
modulo
integer division

<
>
<=
>=
==
!=

lesser than
greater than
lesser than or equal to
greater than or equal to
equal
different

Logical
! x
x & y
x && y
x | y
x || y
xor(x, y)

logical NOT
logical AND
id
...

exclusive OR

The arithmetic and comparison operators act on two elements (x + y, a
< b)
...
The comparison operators may be applied to any
mode: they return one or several logical values
...
The operators “AND” and “OR”
exist in two forms: the single one operates on each elements of the objects and
returns as many logical values as comparisons done; the double one operates
on the first element of the objects
...
The expression 0
< x < 1 is valid, but will not return the expected result: since both operators
are the same, they are executed successively from left to right
...

10

The following characters are also operators for R: $, @, [, [[, :, ?, <-, <<-, =, ::
...


25

> x <- 0
...
To compare ‘wholly’ two objects, two
functions are available: identical and all
...

> x <- 1:3; y <- 1:3
> x == y
[1] TRUE TRUE TRUE
> identical(x, y)
[1] TRUE
> all
...
all
...
The latter function takes the approximation of
the computing process into account when comparing numeric values
...
9 == (1 - 0
...
9, 1 - 0
...
equal(0
...
1)
[1] TRUE
> 0
...
1 - 0
...
9, 1
...
2)
[1] FALSE
> all
...
9, 1
...
2)
[1] TRUE
> all
...
9, 1
...
2, tolerance = 1e-16)
[1] "Mean relative difference: 1
...
5
...
To access, for
example, the third value of a vector x, we just type x[3] which can be used
either to extract or to change this value:
> x <- 1:5
26

> x[3]
[1] 3
> x[3] <- 20
> x
[1] 1 2 20

4

5

The index itself can be a vector of mode numeric:
> i <- c(1, 3)
> x[i]
[1] 1 20
If x is a matrix or a data frame, the value of the ith line and j th column
is accessed with x[i, j]
...

The default behaviour of R is to return an object of the lowest dimension
possible
...
It may
be useful to keep in mind that indexing is made with square brackets, while
parentheses are used for the arguments of a function:
> x(1)
Error: couldn’t find function "x"

27

Indexing can also be used to suppress one or several rows or columns
using negative values
...
Using the matrix
defined above:
> x[, -1]
[,1] [,2]
[1,]
3
21
[2,]
4
22
> x[, -(1:2)]
[1] 21 22
> x[, -(1:2), drop = FALSE]
[,1]
[1,]
21
[2,]
22
For vectors, matrices and arrays, it is possible to access the values of an
element with a comparison expression as the index:
> x <- 1:10
> x[x >= 5]
> x
[1] 1 2
> x[x == 1]
> x
[1] 25 2

<- 20
3 4 20 20 20 20 20 20
<- 25
3

4 20 20 20 20 20 20

A practical use of the logical indexing is, for instance, the possibility to
select the even elements of an integer variable:
> x <- rpois(40, lambda=5)
> x
[1] 5 9 4 7 7 6 4 5 11 3
[21] 4 6 6 5 4 5 3 4 3 3
> x[x %% 2 == 0]
[1] 4 6 4 2 2 2 4 6 6 4 4 8 4 2 4

5
3

7
7

1
7

5
3

3
8

9
1

2
4

2
2

5
1

2
4

Thus, this indexing system uses the logical values returned, in the above
examples, by comparison operators
...

For lists, accessing the different elements (which can be any kind of object)
is done either with single or with double square brackets: the difference is
that with single brackets a list is returned, whereas double brackets extract the
object from the list
...
For instance, if the third object of a list is a vector, its
ith value can be accessed using my
...
list[[3]][i, j, k], and so on
...
list[1:2] will return a list with the first and second elements of the
original list, whereas my
...

3
...
5

Accessing the values of an object with names

The names are labels of the elements of an object, and thus of mode character
...
There are several kinds of names
(names, colnames, rownames, dimnames)
...

> x <- 1:3
> names(x)
NULL
> names(x) <- c("a", "b", "c")
> x
a b c
1 2 3
> names(x)
[1] "a" "b" "c"
> names(x) <- NULL
> x
[1] 1 2 3
For matrices and data frames, colnames and rownames are labels of the
columns and rows, respectively
...

>
>
>
>

X <- matrix(1:4, 2)
rownames(X) <- c("a", "b")
colnames(X) <- c("c", "d")
X
c d
a 1 3
b 2 4
> dimnames(X)
[[1]]
[1] "a" "b"
29

[[2]]
[1] "c" "d"
For arrays, the names of the dimensions can be accessed with dimnames:
> A <- array(1:8, dim = c(2, 2, 2))
> A
, , 1

[1,]
[2,]

[,1] [,2]
1
3
2
4

, , 2

[1,]
[2,]

[,1] [,2]
5
7
6
8

> dimnames(A) <- list(c("a", "b"), c("c", "d"), c("e", "f"))
> A
, , e
c d
a 1 3
b 2 4
, , f
c d
a 5 7
b 6 8
If the elements of an object have names, they can be extracted by using
them as indices
...
For instance,
if a data frame DF contains the variables x, y, and z, the command DF["x"]
will return a data frame with just x; DF[c("x", "y")] will return a data
frame with both variables
...

As the reader surely realizes, the index used here is a vector of mode
character
...

To extract a vector or a factor from a data frame, on can use the operator
$ (e
...
, DF$x)
...

30

3
...
6

The data editor

It is possible to use a graphical spreadsheet-like editor to edit a “data” object
...
entry(X) will open a graphic
editor and one will be able to modify some values by clicking on the appropriate
cells, or to add new columns or rows
...
entry modifies directly the object given as argument
without needing to assign its result
...
This
result is displayed on the screen by default, but, as for most functions, can be
assigned to an object
...

3
...
7

Arithmetics and simple functions

There are numerous functions in R to manipulate data
...
For
example:
> c(1:5, seq(10, 11, 0
...
0 2
...
0 4
...
0 10
...
2 10
...
6 10
...
0
Vectors can be manipulated with classical arithmetic expressions:
> x
> y
> z
> z
[1]

<- 1:4
<- rep(1, 4)
<- x + y
2 3 4 5

Vectors of different lengths can be added; in this case, the shortest vector
is recycled
...
If we want to add (or multiply) the same
value to all the elements of a vector:
> x
> a
> z
> z
[1]

<- 1:4
<- 10
<- a * x
10 20 30 40

The functions available in R for manipulating data are too many to be
listed here
...
), special functions (gamma, digamma, beta, besselI,
...
Some of these functions are listed in the following table
...
max(x)
which
...
than c(min(x), max(x))
number of elements in x
mean of the elements of x
median of the elements of x
variance of the elements of x (calculated on n − 1); if x is
a matrix or a data frame, the variance-covariance matrix is
calculated
correlation matrix of x if it is a matrix or a data frame (1 if x
is a vector)
covariance between x and y, or between the columns of x and
those of y if they are matrices or data frames
linear correlation between x and y, or correlation matrix if they
are matrices or data frames

These functions return a single value (thus a vector of length one), except
range which returns a vector of length two, and var, cov, and cor which may
return a matrix
...


round(x, n)
rev(x)
sort(x)
rank(x)

rounds the elements of x to n decimals
reverses the elements of x
sorts the elements of x in increasing order; to sort in decreasing order:
rev(sort(x))
ranks of the elements of x

32

log(x, base)
scale(x)

pmin(x,y,
...
)
cumsum(x)
cumprod(x)
cummin(x)
cummax(x)
match(x, y)
which(x == a)

choose(n, k)
na
...
fail(x)
unique(x)
table(x)
table(x, y)
subset(x,
...
5
...

id
...
for the product
id
...
for the maximum
returns a vector of the same length than x with the elements of x
which are in y (NA otherwise)
returns a vector of the indices of x if the comparison operation is
true (TRUE), in this example the values of i for which x[i] == a (the
argument of this function must be a variable of mode logical)
computes the combinations of k events among n repetitions = n!/[(n−
k)!k!]
suppresses the observations with missing data (NA) (suppresses the
corresponding line if x is a matrix or a data frame)
returns an error message if x contains at least one NA
if x is a vector or a data frame, returns a similar object but with the
duplicate elements suppressed
returns a table with the numbers of the differents values of x (typically
for integers or factors)
contingency table of x and y
returns a selection of x with respect to criteria (
...
The functions
rbind and cbind bind matrices with respect to the lines or the columns,
respectively:
> m1 <- matrix(1, nr = 2, nc = 2)
> m2 <- matrix(2, nr = 2, nc = 2)
> rbind(m1, m2)
[,1] [,2]
[1,]
1
1
[2,]
1
1
[3,]
2
2
[4,]
2
2
> cbind(m1, m2)
[,1] [,2] [,3] [,4]
33

[1,]
[2,]

1
1

1
1

2
2

2
2

The operator for the product of two matrices is ‘%*%’
...

The function diag can be used to extract or modify the diagonal of a
matrix, or to build a diagonal matrix
...
1, nr = 3, nc = 5)
[,1] [,2] [,3] [,4] [,5]
[1,] 2
...
0 0
...
0 2
...
0
0
0
[3,] 0
...
0 2
...
We can cite
here solve for inverting a matrix, qr for decomposition, eigen for computing
eigenvalues and eigenvectors, and svd for singular value decomposition
...
To get an idea, one can type
demo(graphics) or demo(persp)
...

The way graphical functions work deviates substantially from the scheme
sketched at the beginning of this document
...

A graphical device is a graphical window or a file
...
The graphs are produced with respect to
graphical parameters which are defined by default and can be modified with
the function par
...
We will
see a practical example of the use of these functionalities in producing graphs
...


4
...
1
...
A graphical device may be open with
an appropriate function
...
The graphical windows are called X11 under Unix/Linux
and windows under Windows
...
A graphical device which is a file will be
open with a function depending on the format: postscript(), pdf(), png(),

...

The last open device becomes the active graphical device on which all
subsequent graphs are displayed
...
list() displays the list
of open devices:
> x11(); x11(); pdf()
> dev
...


36

X11 X11 pdf
2
3
4
The figures displayed are the device numbers which must be used to change
the active device
...
cur()
pdf
4
and to change the active device:
> dev
...
off() closes a device: by default the active device is
closed, otherwise this is the one which number is given as argument to the
function
...
off(2)
X11
3
> dev
...
metafile, and
a menu “History” displayed when the graphical window is selected allowing
recording of all graphs drawn during a session (by default, the recording system
is off, the user switches it on by clicking on “Recording” in this menu)
...
1
...
screen partitions the active graphical device
...
screen(c(1, 2))
divides the device into two parts which can be selected with screen(1) or
screen(2); erase
...
A part of the
device can itself be divided with split
...

These functions are incompatible with others (such as layout or coplot)
and must not be used with multiple graphical devices
...

The function layout partitions the active graphic window in several parts
where the graphs will be displayed successively
...
For
example, to divide the device into four equal parts:
37

> layout(matrix(1:4, 2, 2))
It is of course possible to create this matrix previously allowing to better
visualize how the device is divided:
> mat <- matrix(1:4, 2, 2)
> mat
[,1] [,2]
[1,]
1
3
[2,]
2
4
> layout(mat)
To actually visualize the partition created, one can use the function layout
...
In this example, we
will have:

1

3

2

4

> layout
...


1

5

3

> layout(matrix(1:6, 2, 3))
> layout
...
show(6)

6

1

5

2

> m <- matrix(c(1:3, 3), 2, 2)
> layout(m)
> layout
...
,
byrow=TRUE) so that the sub-windows are numbered row-wise
...

By default, layout() partitions the device with regular heights and widths:
this can be modified with the options widths and heights
...
Examples:

> m <- matrix(1:4, 2, 2)
> layout(m, widths=c(1, 3),
heights=c(3, 1))
> layout
...
show(2)

1

Finally, the numbers in the matrix can include zeros giving the possibility
to make complex (or even esoterical) partitions
...
show(3)

1

> m <- matrix(scan(), 5, 5)
1: 0 0 3 3 3 1 1 3 3 3
11: 0 0 3 3 3 0 2 2 0 5
21: 4 2 2 0 5
26:
Read 25 items
> layout(m)
> layout
...


39

4
...


plot(x)
plot(x, y)
sunflowerplot(x,
y)
pie(x)
boxplot(x)
stripchart(x)
coplot(x~y | z)
interaction
...
ts(x)

ts
...
contour (x,
y, z)
image(x, y, z)
persp(x, y, z)
stars(x)

plot of the values of x (on the y-axis) ordered on the x-axis
bivariate plot of x (on the x-axis) and y (on the y-axis)
id
...
the first one of y, the
second one of x vs
...

if x is a data frame, plots a Cleveland dot plot (stacked plots
line-by-line and column-by-column)
visualizes, with quarters of circles, the association between two
dichotomous variables for different populations (x must be an
array with dim=c(2, 2, k), or a matrix with dim=c(2, 2) if
k = 1)
Cohen–Friendly graph showing the deviations from independence of rows and columns in a two dimensional contingency
table
‘mosaic’ graph of the residuals from a log-linear regression of a
contingency table
if x is a matrix or a data frame, draws all possible bivariate plots
between the columns of x
if x is an object of class "ts", plot of x with respect to time, x
may be multivariate but the series must have the same frequency
and dates
id
...
but the areas between the contours are coloured, and a legend
of the colours is drawn as well
id
...
but in perspective
if x is a matrix or a data frame, draws a graph with segments
or a star where each row of x is represented by a star and the
columns are the lengths of the segments

40

symbols(x, y,
...
obj)

draws, at the coordinates given by x and y, symbols (circles,
squares, rectangles, stars, thermometres or “boxplots”) which
sizes, colours, etc, are specified by supplementary arguments
plot of the (partial) effects of a regression model (mod
...

Some of these options are identical for several graphical functions; here are
the main ones (with their possible default values):
add=FALSE
axes=TRUE
type="p"

xlim=, ylim=
xlab=, ylab=
main=
sub=

4
...
but the lines are over
the points, "h": vertical lines, "s": steps, the data are
represented by the top of the vertical lines, "S": id
...
Here are the main ones:

points(x, y)
lines(x, y)
text(x, y, labels,

...
)
segments(x0, y0,
x1, y1)
arrows(x0, y0,
x1, y1, angle= 30,
code=2)
abline(a,b)
abline(h=y)
abline(v=x)
abline(lm
...
but with lines
adds text given by labels at coordinates (x,y); a typical use is:
plot(x, y, type="n"); text(x, y, names)
adds text given by text in the margin specified by side (see
axis() below); line specifies the line from the plotting area
draws lines from points (x0,y0) to points (x1,y1)
id
...
obj (see section 5)

41

rect(x1, y1, x2,
y2)
polygon(x, y)
legend(x, y,
legend)
title()
axis(side, vect)

box()
rug(x)
locator(n,
type="n",
...
); by default nothing is drawn (type="n")

Note the possibility to add mathematical expressions on a plot with text(x,
y, expression(
...
For example,
> text(x, y, expression(p == over(1, 1+e^-(beta*x+alpha))))
will display, on the plot, the following equation at the point of coordinates
(x, y):
1
1 + e−(β x+α)
To include in an expression a variable we can use the functions substitute
and as
...
expression(substitute(R^2==r, list(r=Rsquared))))
will display on the plot at the point of coordinates (x, y):
R2 = 0
...
expression(substitute(R^2==r,
+
list(r=round(Rsquared, 3)))))
will display:
R2 = 0
...
expression(substitute(italic(R)^2==r,
+
list(r=round(Rsquared, 3)))))
R2 = 0
...
4

Graphical parameters

In addition to low-level plotting commands, the presentation of graphics can
be improved with graphical parameters
...
e
...
For instance,
the following command:
> par(bg="yellow")
will result in all subsequent plots drawn with a yellow background
...
The
exhaustive list of these parameters can be read with ?par; I will limit the
following table to the most usual ones
...
5 is centred, 1 is right-justified, values > 1 move the text
further to the left, and negative values further to the right; if two values are
given (e
...
, c(0, 0)) the second one controls vertical justification with respect
to the text baseline
specifies the colour of the background (e
...
, bg="red", bg="blue"; the list of
the 657 available colours is displayed with colors())
controls the type of box drawn around the plot, allowed values are: "o",
"l", "7", "c", "u" ou "]" (the box looks like the corresponding character); if
bty="n" the box is not drawn
a value controlling the size of texts and symbols with respect to the default; the
following parameters have the same control for numbers on the axes, cex
...
lab, the title, cex
...
sub
controls the colour of symbols; as for cex there are: col
...
lab,
col
...
sub
an integer which controls the style of text (1: normal, 2: italics, 3: bold, 4:
bold italics); as for cex there are: font
...
lab, font
...
sub
an integer which controls the orientation of the axis labels (0: parallel to the
axes, 1: horizontal, 2: perpendicular to the axes, 3: vertical)
controls the type of lines, can be an integer (1: solid, 2: dashed, 3: dotted,
4: dotdash, 5: longdash, 6: twodash), or a string of up to eight characters
(between "0" and "9") which specifies alternatively the length, in points or
pixels, of the drawn elements and the blanks, for example lty="44" will have
the same effet than lty=2
a numeric which controls the width of lines
a vector of 4 numeric values which control the space between the axes and the
border of the graph of the form c(bottom, left, top, right), the default
values are c(5
...
1, 4
...
1)
a vector of the form c(nr,nc) which partitions the graphic window as a matrix of nr lines and nc columns, the plots are then drawn in columns (see
section 4
...
2)
id
...
1
...
2)
an integer which controls the size in points of texts and symbols

43

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

"*"

"?"

"
...
The colours were obtained
with the options col="blue", bg="yellow", the second option has an effect
only for the symbols 21–25
...
",

...
5

a character which specifies the type of the plotting region, "s": square, "m":
maximal
a value which specifies the length of tick-marks on the axes as a fraction of
the smallest of the width or height of the plot; if tck=1 a grid is drawn
id
...
5)
if xaxt="n" the x-axis is set but not drawn (useful in conjunction with
axis(side=1,
...
))

A practical example

In order to illustrate R’s graphical functionalities, let us consider a simple
example of a bivariate graph of 10 pairs of random variates
...
The result
is shown on Fig
...
By default, R makes graphs in an “intelligent” way:
44

0
...
0
−1
...
5

y

−0
...
0

0
...
0

x

Figure 3: The function plot used without options
...

The user may, nevertheless, change the way a graph is presented, for instance, to conform to a pre-defined editorial style, or to give it a personal
touch for a talk
...
In our example, we can
modify significantly the figure in the following way:
plot(x, y, xlab="Ten random values", ylab="Ten other values",
xlim=c(-2, 2), ylim=c(-2, 2), pch=22, col="red",
bg="yellow", bty="l", tcl=0
...
5)
The result is on Fig
...
Let us detail each of the used options
...
Then, xlim and ylim allow us to define the limits on both axes 13
...
The table of graphical parameters gives the
meaning of the modifications done by bty, tcl, las and cex
...

The graphical parameters and the low-level plotting functions allow us to
go further in the presentation of a graph
...

13

By default, R adds 4% on each side of the axis limit
...


45

How to customize a plot with R
2

Ten other values

1

0

−1

−2
−2

−1

0

1

2

Ten random values

Figure 4: The function plot used with options
...
When the graphical parameters are changed, it
is useful to save their initial values beforehand to be able to restore them
afterwards
...
5
...
axis="blue", mar=c(4, 4, 2
...
25))
plot(x, y, xlab="Ten random values", ylab="Ten other values",
xlim=c(-2, 2), ylim=c(-2, 2), pch=22, col="red", bg="yellow",
bty="l", tcl=-
...
5)
title("How to customize a plot with R (bis)", font
...
First, the default
graphical parameters are copied in a list called here opar
...
axis for the
colour of the numbers on the axes, and mar for the sizes of the margins around
the plotting region
...
4
...

The title here is added with the low-level plotting function title which allows
to give some parameters as arguments without altering the rest of the graph
...

Now, total control! On Fig
...
We will see now how to totally control the presentation of the
graph
...
,
type="n"), then to add points, axes, labels, etc, with low-level plotting func46

How to customize a plot with R (bis)
2

Ten other values

1

0

−1

−2
−2

−1

0

1

2

Ten random values

Figure 5: The functions par, plot and title
...
We will fancy a few arrangements such as changing the colour of the
plotting area
...
6
...
5, 1
...
5, 0
...
2, labels=FALSE)
axis(side=2, -1:1, tcl=-0
...
main=4, adj=1, cex
...
9, font=3)
mtext("Ten other values", line=0
...
8, cex=0
...
3,
col="blue", cex=0
...
2, col="blue", cex=0
...
The graph is then drawn
with type="n" to not plot the points, xlab="", ylab="" to not write the
axis labels, and xaxt="n", yaxt="n" to not draw the axes
...
Note that we could have used the option axes=FALSE
but in this case neither the axes, nor the box would have been drawn
...


The elements are then added in the plotting region so defined with some
low-level plotting functions
...

The points are plotted with points(); a new symbol was used
...
The option labels=FALSE specifies that no
annotation must be written with the tick-marks
...

The title is added with title(), but the font is slightly changed
...
The first
argument of this function is a vector of mode character giving the text to be
written
...
The second call to mtext() uses
the default value of side (3)
...


4
...
Grid is
a new graphical mode with its own system of graphical parameters which are
distinct from those seen above
...
g
...

Grid graphics cannot usually be combined or mixed with base graphics
(the gridBase package must be used to do this)
...

Lattice is essentially the implementation in R of the Trellis graphics of
S-PLUS
...
The main idea behind lattice (and Trellis as well) is that of conditional multiple graphs: a bivariate graph will be split in several graphs with
respect to the values of a third variable
...
Lattice uses the grid
graphical mode
...
The formula y ~ x | z means that the graph of y with
respect to x will be plotted as several graphs with respect to the values of z
...
The formula given
as argument is the typical necessary formula, but all these functions accept
a conditional formula (y ~ x | z) as main argument; in the latter case, a
multiple graph, with respect to the values of z, is plotted as will be seen in
the examples below
...
(surface)
matrix of bivariate plots
parallel coordinates plot

Let us see now some examples in order to illustrate a few aspects of lattice
...
bell-labs
...
html
plot() also accepts a formula as its main argument: if x and y are two vectors of the
same length, plot(y ~ x) and plot(x, y) will give identical graphs
...
6
0
...
4
0
...
2
0
...
6

Density

0
...
4
0
...
2
0
...
6
0
...
4
0
...
2
0
...


so that the functions can be accessed
...
Such graphs can be
done simply with densityplot(~ x) which will plot a curve of the empirical
density function with the points corresponding to the observations on the xaxis (similarly to rug())
...
It is necessary to use the argument panel which
defines what is drawn on each plot
...
) {
panel
...
)
panel
...
, and
45
...

panel takes as argument a function
...
densityplot to
draw the empirical density function, and panel
...
The function panel
...


(~ x | y) would have resulted in the same graph than Fig
...

The next examples are taken, more or less modified, from the help pages
of lattice, and use some data sets available in R: the locations of 1000 seismic
events near the Fiji Islands, and some flower measurements made on three
species of iris
...
8 shows the geographic locations of the seismic events with respect to
depth
...
cat <- factor(floor(((quakes$depth - mini) / int)),
labels=paste(inf, inf + int, sep="-"))
xyplot(lat ~ long | depth
...
The five next commands create a factor by dividing the depth (variable depth) in nine equallyranged intervals: the levels of this factor are labelled with the lower and upper
bounds of these intervals
...

With the data iris, the overlap among the different species is sufficiently
small so they can be plotted on the figure (Fig
...
The commands are:
16

plot() cannot take an argument data, the location of the variables must be given
explicitly, for example plot(quakes$long ~ quakes$lat)
...
Length

o

o
o

4

o
o
o

o
o

o
o
o
o

o
o
o
o
o
o
o

o
o
o
o

o
o
o
o
o
o

o
o
o

o

o
o
o

o

o

o
o

o
o
o

o
o
o
o
o
o
o
o
o

o
o

o
o
o
o
o
o
o

o
o
o

o

o

o

o
o

o

o

3

2
o
o
o

1

0

o
o
o
o
o
o
o
o

o
o
o
o

o
o
o
o
o

o

0
...
5

2

2
...
Width

Figure 9: The function xyplot with the data “iris”
...
Length ~ Petal
...
superpose,
type = c("p", "smooth"), span=
...
key = list(x = 0
...
85)
)
The call to the function xyplot is here a bit more complex than in the
previous example and uses several options that we will detail
...
We have already seen the option panel which defines how the
different groups will be represented on the graph: we use here a pre-defined
function panel
...

No option is passed to panel
...
The option type, like in plot(), specifies how the
data are represented, but here we can give several arguments as a vector:
"p" to draw points and "smooth" to draw a smooth curve which degree of
smoothness is specified by span
...
key adds a legend to the
graph: it is only necessary to give, as a list, the coordinates where the legend
is to be plotted
...
e
...

We will see now the function splom with the same data on iris
...
10:
splom(
~iris[1:4], groups = Species, data = iris, xlab = "",
panel = panel
...
5

1
...
Length

6
5

5

6

o o
o oooo oo
oooooooooooooo o 1
o
o

o
4
...
5

4

4
3
...
Width

2
2

4
...
5

o
2
o
o
ooo
o
oo
oo
oo o
oo
o oooooo
o
o
o o
oooooo
oo
oo oooooo oo
o
oooo o
o
o
ooooo o
o o o oo
o
oo o o
ooo oooo oo o o o
oo o
oo
o
o
o
o
oo o
oo
o
o
oo
o
o o o ooooooo o
o
o ooo
oo o
oo
o
o
oo oo o
o
ooo
o
ooo
oo o o
o
ooo
o
o
oo o
o
o
o
o

2

2
...
5

Petal
...
Length 4
ooooooooo
o oo o
oo
o
ooo
o o
o oo o o
o
o
o
3
o
o

ooo
o
o o oo o o
oo o oo o o
oo
oo o o o o
o
o
ooo
oo
ooo
o
o
oo o
o o oo o
o
o
o o oo o o o o
o
o
o oo
oo
oo o o
o o oo o o
o o o o o o oo o oo o o o o
o o o oooo
o o o oo
o o o oo o o oo o o o
o ooo o
o
o oo o
oo
oo o
o
oo oo oo o
oo
oo
o o o oo
o
o
o
8
7
8

1
...
5
0
...


auto
...

The result is the set of possible bivariate plots among the columns of the
matrix, like the standard function pairs
...
The other options are similar to the previous example, except that
columns = 3 for auto
...

Fig
...
11
...

The last example uses the method of parallel coordinates for the exploratory analysis of multivariate data
...
g
...
g
...
The different
values of the same individual are joined by a line
...
12
is obtained with the following code:
parallel(~iris[, 1:4] | Species, data = iris, layout = c(3, 1))

53

virginica
Petal
Length

Sepal
Width

Sepal
Length
setosa

versicolor
Petal
Length

Petal
Length

Sepal
Width

Sepal
Width

Sepal
Length

Sepal
Length
Scatter Plot Matrix

Figure 11: The function splom with the data “iris” (2)
...
Width

Petal
...
Width

Sepal
...


54

5

Statistical analyses with R

Even more than for graphics, it is impossible here to go in the details of the
possibilities offered by R with respect to statistical analyses
...

The package stats contains functions for a wide range of basic statistical analyses: classical tests, linear models (including least-squares regression,
generalized linear models, and analysis of variance), distributions, summary
statistics, hierarchical clustering, time-series analysis, nonlinear least squares,
and multivariate analysis
...
Some of them are distributed with a base installation
of R and are labelled recommanded, and many other packages are contributed
and must be installed by the user
...
Then,
we will detail some notions, formulae and generic functions, which are useful
whatever the type of analysis performed
...


5
...
In order to try it, let
us take a data set distributed with R: InsectSprays
...

Each insecticide was tested 12 times, thus there are 72 observations
...
After
loading the data in memory with the function data, the analysis is performed
after a square-root transformation of the response:
> data(InsectSprays)
> aov
...
The option data = InsectSprays specifies that the
variables must be found in the data frame InsectSprays
...
spray <- aov(sqrt(InsectSprays$count) ~ InsectSprays$spray)
or still (if we know the column numbers of the variables):
55

> aov
...

The results are not displayed since they are assigned to an object called
aov
...
We will then used some functions to extract the results, for example print to display a brief summary of the analysis (mostly the estimated parameters) and summary to display more details (included the statistical tests):
> aov
...
43787 26
...
of Freedom
5
66
Residual standard error: 0
...
spray)
Df Sum Sq Mean Sq F value
Pr(>F)
spray
5 88
...
688 44
...
2e-16 ***
Residuals
66 26
...
395
--Signif
...
001 ‘**’ 0
...
05 ‘
...
1 ‘ ’ 1
We may remind that typing the name of the object as a command is similar
to the command print(aov
...
A graphical representation of the results
can be done with plot() or termplot()
...
spray) we
will divide the graphics into four parts so that the four diagnostics plots will
be done on the same graph
...
spray)
par(opar)
termplot(aov
...
resid=TRUE, rug=TRUE)

and the resulting graphics are on Figs
...


5
...
A formula is typically of the form y
~ model where y is the analysed response and model is a set of terms for
which some parameters are to be estimated
...

56

1
...
5

0
...
5

1
...
08

27
25

0

Theoretical Quantiles

39

0
...
5

0
...
5
Fitted values

Normal Q−Q plot

−2

Standardized residuals

Fitted values

−2

39

1
...
5

Scale−Location plot
27
25

0
...
0

39

0
...
5

Residuals

Residuals vs Fitted
27

20

40

60

Obs
...


a+b
X

a:b
a*b
poly(a, n)
^n
b %in% a
-b
-1
1
offset(
...
e
...
+X[,ncol(X)]; some
of the columns may be selected with numeric indices (e
...
,
X[,2:4])
interactive effect between a and b
additive and interactive effects (identical to a+b+a:b)
polynomials of a up to degree n
includes all interactions up to level n, i
...
(a+b+c)^2 is
identical to a+b+c+a:b+a:c+b:c
the effects of b are nested in a (identical to a+a:b, or
a/b)
removes the effect of b, for example: (a+b+c)^2-a:b is
identical to a+b+c+a:c+b:c
y~x-1 is a regression through the origin (id
...
g
...
For example, the formula y~x1+x2
defines the model y = β1 x1 + β2 x2 + α, and not (if the operator + would have
its usual meaning) y = β(x1 + x2 ) + α
...
Similarly, to define the model y = β 1 x + β2 x2 + α, we
will use the formula y ~ poly(x, 2) (and not y ~ x + x^2)
...


possible to include a function in a formula in order to transform a variable as
seen above with the insect sprays analysis of variance
...
For instance, y ~ a + Error(b) means the additive effects of
the fixed term a and the random one b
...
3

Generic functions

We remember that R’s functions act with respect to the attributes of the
objects possibly passed as arguments
...
It is very common that the R statistical functions return an
object of class with the same name (e
...
, aov returns an object of class "aov",
lm returns one of class "lm")
...

These functions are called generic
...
Whether the object given
as argument is of class "lm" (linear model) or "aov" (analysis of variance),
it sounds obvious that the information to display will not be the same
...

An object containing the results of an analysis is generally a list, and the
way it is displayed is determined by its class
...

It is a general feature of R17
...


58

tions which can be used to extract information from objects resulting from an
analysis
...
residual(mod)
[1] 8

print
summary
df
...
If we take our example of an analysis
of variance with the data InsectSprays, we can look at the structure of the
object returned by aov:
> str(aov
...
level = -1)
List of 13
- attr(*, "class")= chr [1:2] "aov" "lm"
Another way to look at this structure is to display the names of the object:
> names(aov
...
values"
"df
...
spray$coefficients
(Intercept)
sprayB
sprayC
3
...
1159530 -2
...
9512174
0
...
5963245

summary() also creates a list which, in the case of aov(), is simply a table
of tests:

59

> str(summary(aov
...
frame’:
2 obs
...
$ Df
: num [1:2] 5 66

...
4 26
...
$ Mean Sq: num [1:2] 17
...
395

...
8
NA

...
aov" "listof"
> names(summary(aov
...
A
function called by a generic is a method in R’s jargon
...
cls , where cls is the class of the object
...
aovlist"
[5] "summary
...
frame"
[7] "summary
...
glm
...
lm"
[13] "summary
...
mlm"
[17] "summary
...
table"

"summary
...
connection"
"summary
...
glm"
"summary
...
lm
...
matrix"
"summary
...
POSIXlt"

We can see the difference for this generic in the case of a linear regression,
compared to an analysis of variance, with a small simulated example:
> x <- y <- rnorm(5)
> lm
...
spray)
[1] "coefficients" "residuals"
[4] "rank"
"fitted
...
residual"
[10] "call"
"terms"
> names(summary(lm
...
squared"
"adj
...
squared"
[10] "cov
...

add1
drop1
step
anova
predict
update

tests successively all the terms that can be added to a model
tests successively all the terms that can be removed from a model
selects a model with AIC (calls add1 and drop1)
computes a table of analysis of variance or deviance for one or several
models
computes the predicted values for new data from a fitted model
re-fits a model with a new formula or new data

There are also various utilities functions that extract information from a
model object or a formula, such as alias which finds the linearly dependent
terms in a linear model specified by a formula
...


5
...
Some of them are loaded in memory when R starts; this
can be displayed with the function search:
> search()
[1] "
...
The information relative to each
function can be accessed as previously seen (p
...


61

Package

Description

base
datasets
grDevices
graphics
grid
methods

base R functions
base R datasets
graphics devices for base and grid graphics
base graphics
grid graphics
definition of methods and classes for R objects and programming tools
regression spline functions and classes
statistical functions
statistical functions using S4 classes
functions to interface R with Tcl/Tk graphical user interface
elements
tools for package development and administration
R utility functions

splines
stats
stats4
tcltk
tools
utils

Many contributed packages add to the list of statistical methods available
in R
...
A complete list of the contributed packages, with descriptions, is on the
CRAN Web site18
...
The recommended packages
are often distributed with a base installation of R
...

Package

Description

boot
class
cluster
foreign

resampling and bootstraping methods
classification methods
clustering methods
functions for reading data stored in various formats (S3,
Stata, SAS, Minitab, SPSS, Epi Info)
methods for kernel smoothing and density estimation (including bivariate kernels)
Lattice (Trellis) graphics
contains many functions, tools and data sets from the libraries of “Modern Applied Statistics with S” by Venables
& Ripley
generalized additive models
linear and non-linear mixed-effects models
neural networks and multinomial log-linear models
recursive partitioning
spatial analyses (“kriging”, spatial covariance,
...
r-project
...
html

62

There are two other main repositories of R packages: the Omegahat Project
for Statistical Computing19 which focuses on web-based applications and interfaces between softwares and languages, and the Bioconductor Project 20
specialized in bioinformatic applications (particularly for the analysis of microarray data)
...
In the
latter situation, it is recommended to use the pre-compiled packages available
on CRAN’s site
...
exe has a menu “Packages”
allowing to install packages via internet from the CRAN Web site, or from
zipped files on the local disk
...
tar
...
For instance, if we want to install the package gee,
we will first download the file gee 4
...
tar
...
13-6 indicates
the version of the package; generally only one version is available on CRAN)
...
13-6
...
gz
There are several useful functions to manage packages such as installed
...
packages, or download
...
It is also useful to type
regularly the command:
> update
...
The user can then update the packages with more recent versions
than those installed on the computer
...
omegahat
...
bioconductor
...
We will see a few simple ideas likely to be used
in practice
...
1

Loops and vectorization

An advantage of R compared to softwares with pull-down menus is the possibility to program simply a series of analyses which will be executed successively
...

Like other languages, R has some control structures which are not dissimilar to those of the C language
...
We first create a vector y of the same length than x:
y <- numeric(length(x))
for (i in 1:length(x)) if (x[i] == b) y[i] <- 0 else y[i] <- 1
Several instructions can be executed if they are placed within braces:
for (i in 1:length(x)) {
y[i] <- 0

...

}
Another possible situation is to execute an instruction as long as a condition is true:
while (myfun > minimum) {

...
Vectorization makes loops implicit in
expression, and we have seen many cases
...
We realize that this explicit loop will work
only if x and y are of the same length: it must be changed if this is not true,
whereas the first expression will work in all situations
...
else) can be avoided with the use
of the logical indexing; coming back to the above example:
> y[x == b] <- 0
> y[x != b] <- 1
In addition to being simpler, vectorized expressions are computationally
more efficient, particularly with large quantities of data
...
apply acts on the rows and/or columns of a matrix, its syntax is
apply(X, MARGIN, FUN,
...
are possible optional arguments for FUN
...

>
>
>
>

x <- rnorm(10, -5, 0
...
975132 4
...
0755153 2
...

> forms <- list(y ~ x, y ~ poly(x, 2))
> lapply(forms, lm)
[[1]]
Call:
FUN(formula = X[[1]])
Coefficients:
65

(Intercept)
31
...
377

[[2]]
Call:
FUN(formula = X[[2]])
Coefficients:
(Intercept) poly(x, 2)1
4
...
2181

poly(x, 2)2
-0
...


6
...
R’
...
In our first example, we want
to do the same plot for three different species of birds, the data being in three
distinct files
...

First, let us make our program in the most intuitive way by executing successively the needed commands, taking care to partition the graphical device
beforehand
...
table("Swal
...
table("Wren
...
table("Dunn
...

The problem of this first program is that it may become quite long if we
want to add other species
...
The strategy used here is to put these arguments in vectors of
mode character, and then use the indexing to access these different values
...
dat" , "Wren
...
dat")
for(i in 1:length(species)) {
data <- read
...
table()
since this argument is of mode character
...
It is easier to add other species since
the vectors containing the species and file names are at the beginning of the
program
...
dat’ are located
in the working directory of R, otherwise the user must either change the working directory, or specifiy the path in the program (for example: file <"/home/paradis/data/Swal
...
If the program is written in the file Mybirds
...
R")
Like for any input from a file, it is necessary to give the path to access the
file if it is not in the working directory
...
3

Writing your own functions

We have seen that most of R’s work is done with functions which arguments
are given within parentheses
...

Writing your own functions allows an efficient, flexible, and rational use of
R
...
If we want to do this operation in different situations, it may be a
good idea to write a function:
myfun <- function(S, F)
{
data <- read
...
The lines of the function can be typed directly on the
keyboard, like any other command, or copied and pasted from an editor
...
If the user wants some functions to be loaded each
time when R starts, they can be saved in a workspace
...
Another possibility is to
configure the file ‘
...
Finally,
it is possible to create a package, but this will not be discussed here (see the
manual “Writing R Extensions”)
...
dat")
...
dat")
myfun("wren", "Wrenn
...
dat")
We may also use sapply() leading to a fourth version of our program:
layout(matrix(1:3, 3, 1))
species <- c("swallow", "wren", "dunnock")
file <- c("Swal
...
dat", "Dunn
...

When a function is executed, R uses a rule called lexical scoping to decide
whether an object is local to the function, or global
...

If x is used as the name of an object within our function, the value of x in
the global environment is not used
...

68

The word “enclosing” above is important
...
If there are three or more nested environments, the search for the
objects is made progressively from a given environment to the enclosing one,
and so on, up to the global one
...
For example, let us consider
a function with three arguments:
foo <- function(arg1, arg2, arg3) {
...
, if the corresponding objects are placed in the correct position, for instance: foo(x, y,
z)
...
g
...
Another feature of
R’s functions is the possibility to use default values in their definition
...
}
The commands foo(x), foo(x, 5, FALSE), and foo(x, arg3 = FALSE) will
have exactly the same result
...
e
...

To conclude this section, let us see another example which is not purely
statistical, but it illustrates the flexibility of R
...
We
want, using a function, to simulate this model with respect to the growth rate
r and the initial number in the population N 0 (the carrying capacity K is
often taken equal to 1 and this value will be taken as default); the results will
be displayed as a plot of numbers with respect to time
...
The function below can do this numerical
analysis of Ricker’s model
...
1, 1); title("r = 1")
ricker(0
...
1, 3); title("r = 3")

70

7

Literature on R

Manuals
...
pdf],
• R Installation and Administration [R-admin
...
pdf],
• Writing R Extensions [R-exts
...
pdf]
...
) depending on
the type of installation
...
R is also distributed with an FAQ (Frequently Asked Questions) localized in the directory R HOME/doc/html/
...
r-project
...
html
On-line resources
...
There are also a list of publications (books and articles) about R or statistical methods 21 and some
documents and tutorials written by R’s users 22
...
There are four discussion lists on R; to subscribe, send a message, or read the archives see: http://www
...
org/mail
...

The general discussion list ‘r-help’ is an interesting source of information
for the users of R (the three other lists are dedicated to annoucements
of new versions, and for developers)
...
If a problem
is encountered with R, it is thus important to proceed in the following
order before sending a message to ‘r-help’:
1
...
read the R-FAQ;
3
...
read the “posting guide”24 before sending your question(s)
...
R-project
...
html
http://cran
...
org/other-docs
...
r-project
...
html
24
http://www
...
org/posting-guide
...
The electronic journal R News aims to fill the gap between the
electronic discussion lists and traditional scientific publications
...

Citing R in a publication
...
R: A language and environment for statistical computing
...
ISBN 3-900051-07-0, URL:
http://www
...
org
...
r-project
Title: R for beginners
Description: just to know the basic of R(Big Data)