0% found this document useful (0 votes)
4 views115 pages

Introduction to R Programming Basics

This document provides an introduction and overview of R, an open-source statistical software and programming language. It covers the basics of R including types of objects, basic object handling, and advanced object handling. It also discusses graphics, functions, modelling tools, and more advanced techniques. The document is intended to introduce newcomers to R and provide a high-level plan of what will be covered.

Uploaded by

winkhaing
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views115 pages

Introduction to R Programming Basics

This document provides an introduction and overview of R, an open-source statistical software and programming language. It covers the basics of R including types of objects, basic object handling, and advanced object handling. It also discusses graphics, functions, modelling tools, and more advanced techniques. The document is intended to introduce newcomers to R and provide a high-level plan of what will be covered.

Uploaded by

winkhaing
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Introduction Basics Graphics Functions Modelling tools Getting fancy

An introduction to

Thibaut Jombart

MRC Centre for Outbreak Analysis and Modelling


Imperial College London

16 November 2015

1/95
Introduction Basics Graphics Functions Modelling tools Getting fancy

Outline

Introduction

Basics

Graphics

Functions

Modelling tools

Getting fancy

2/95
Introduction Basics Graphics Functions Modelling tools Getting fancy

Plan
Introduction
Basics
Types of objects
Basic object handling
Advanced object handling
Graphics
Basic graphics
ggplot2
Functions
Modelling tools
Linear models
Distributions
Optimization
Getting fancy
3/95
Introduction Basics Graphics Functions Modelling tools Getting fancy

What is ?

• a free software for data analysis


• an interpreted programming language, derived from ‘S-plus’
• initially developed by R. Ihaka and R. Gentleman (1996)
• currently developed by the R Core Team (∼20 people)
• largest collection of tools for statistics and data analysis
(1,000s of contributors)

4/95
Introduction Basics Graphics Functions Modelling tools Getting fancy

Where can you get it?

• google ‘R’
• The project: [Link]/
• distribution on CRAN: [Link]/[Link]
• available on Windows, MacOSX, Linux

5/95
Introduction Basics Graphics Functions Modelling tools Getting fancy

What does it do?


Base , core packages (30), and regular packages (>6,000):
• probability distributions
• statistical tests
• linear/non-linear modelling
• multivariate analysis
• time series
• spatial statistics
• graph theory
• genetics
• ...
See ‘task views’: [Link]/web/views/

6/95
Introduction Basics Graphics Functions Modelling tools Getting fancy

How much is it free?

is free in the sense of free software (GPL):


• you don’t pay for it
• the sources are freely accessible
• anyone can re-use, modify and distribute the code

7/95
Introduction Basics Graphics Functions Modelling tools Getting fancy

Getting started

All you need is:


• for your system (download from CRAN)
• a text editor to write code: notepad++, emacs, vi, Tinn-R, ...
• a Graphical User Interface (GUI): RStudio, Tinn-R, ESS

8/95
Introduction Basics Graphics Functions Modelling tools Getting fancy

And then...
Things look like this. Not so pretty.

9/95
Introduction Basics Graphics Functions Modelling tools Getting fancy

Getting help
Different ways of getting help:
• ?foo/help("foo"): access the help page
of foo
• ??bar/[Link]("foo"): look for
foo in help pages
• RSiteSearch("foo"): search foo in
help pages & forum archives
• dedicated mailing lists:
[Link]/mailman/listinfo
• The -epi project:
[Link]/site/
therepiproject

10/95
Introduction Basics Graphics Functions Modelling tools Getting fancy

Plan
Introduction
Basics
Types of objects
Basic object handling
Advanced object handling
Graphics
Basic graphics
ggplot2
Functions
Modelling tools
Linear models
Distributions
Optimization
Getting fancy
11/95
Introduction Basics Graphics Functions Modelling tools Getting fancy

How does work?

• code is not compiled, but interpreted


• no file, all in the RAM
• content of a session can be saved using save/[Link]
(output: .RData file)
• .RData files can be loaded using load
• data, results, functions, etc. are all objects
12/95
Introduction Basics Graphics Functions Modelling tools Getting fancy

How does work?

• code is not compiled, but interpreted


• no file, all in the RAM
• content of a session can be saved using save/[Link]
(output: .RData file)
• .RData files can be loaded using load
• data, results, functions, etc. are all objects
12/95
Introduction Basics Graphics Functions Modelling tools Getting fancy

How does work?

• code is not compiled, but interpreted


• no file, all in the RAM
• content of a session can be saved using save/[Link]
(output: .RData file)
• .RData files can be loaded using load
• data, results, functions, etc. are all objects
12/95
Introduction Basics Graphics Functions Modelling tools Getting fancy

How does work?

• code is not compiled, but interpreted


• no file, all in the RAM
• content of a session can be saved using save/[Link]
(output: .RData file)
• .RData files can be loaded using load
• data, results, functions, etc. are all objects
12/95
Introduction Basics Graphics Functions Modelling tools Getting fancy

How does work?

• code is not compiled, but interpreted


• no file, all in the RAM
• content of a session can be saved using save/[Link]
(output: .RData file)
• .RData files can be loaded using load
• data, results, functions, etc. are all objects
12/95
Introduction Basics Graphics Functions Modelling tools Getting fancy

How does work?

• code is not compiled, but interpreted


• no file, all in the RAM
• content of a session can be saved using save/[Link]
(output: .RData file)
• .RData files can be loaded using load
• data, results, functions, etc. are all objects
12/95
Introduction Basics Graphics Functions Modelling tools Getting fancy

Basic objects 1: numbers


Numbers can be integer or numeric:
> a <- 1:10
> a

[1] 1 2 3 4 5 6 7 8 9 10

> class(a)

[1] "integer"

> b <- a + 0.1


> b

[1] 1.1 2.1 3.1 4.1 5.1 6.1 7.1 8.1 9.1 10.1

> class(b)

[1] "numeric"

13/95
Introduction Basics Graphics Functions Modelling tools Getting fancy

Basic objects 2: characters

Character strings are character:


> a <- "hello world"
> a

[1] "hello world"

> class(a)

[1] "character"

14/95
Introduction Basics Graphics Functions Modelling tools Getting fancy

Basic objects 3: categorical variables


Categorical variables are factor:
> a <- factor(c("red","blue","green","red","green"))
> a

[1] red blue green red green


Levels: blue green red

> class(a)

[1] "factor"

> levels(a)

[1] "blue" "green" "red"

15/95
Introduction Basics Graphics Functions Modelling tools Getting fancy

Basic objects 4: booleans

Booleans (TRUE/FALSE) are logical:


> a <- c(TRUE,FALSE,TRUE,TRUE)
> a

[1] TRUE FALSE TRUE TRUE

> class(a)

[1] "logical"

16/95
Introduction Basics Graphics Functions Modelling tools Getting fancy

Vectors
Vectors contain series of values of a given type:
> a <- c(1,2,10,-1, 1.123)
> a

[1] 1.000 2.000 10.000 -1.000 1.123

> class(a)

[1] "numeric"

> [Link](a)

[1] TRUE

> length(a)

[1] 5

17/95
Introduction Basics Graphics Functions Modelling tools Getting fancy

Matrices
Matrices contain series of values of a given type, in a table:
> a <- matrix(sample(1:12),ncol=4)
> a

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


[1,] 6 4 11 8
[2,] 2 5 9 12
[3,] 3 1 10 7

> class(a)

[1] "matrix"

> [Link](a)

[1] TRUE

> dim(a)

[1] 3 4
18/95
Introduction Basics Graphics Functions Modelling tools Getting fancy

Data frames
A [Link] is a table where different variables (columns) can
have different types:
> a <- [Link](age=c(10,54,3), sex=c("m","f","m"))
> a

age sex
1 10 m
2 54 f
3 3 m

> class(a)

[1] "[Link]"

> dim(a)

[1] 3 2

19/95
Introduction Basics Graphics Functions Modelling tools Getting fancy

Lists
A list can store any collection of objects of any types in different
slots:
> a <- list(age=c(10,54,3), sex=c("m","f","m"),
+ swab=matrix(sample(c("+","-"),replace=TRUE, 10), nrow=2,
+ dimnames=list(NULL, paste("t",1:5,sep=""))))
> a

$age
[1] 10 54 3

$sex
[1] "m" "f" "m"

$swab
t1 t2 t3 t4 t5
[1,] "+" "+" "-" "-" "+"
[2,] "-" "+" "+" "+" "+"

> class(a)

[1] "list"

> length(a)

[1] 3
20/95
Introduction Basics Graphics Functions Modelling tools Getting fancy

Summary: basic object types

• integer: integer numbers


• numeric: decimal numbers
• character: character strings
• factor: categorical variables
• vector: collection of values (same type)
• matrix: collection of values (table, same type)
• [Link]: table where columns can have different types,
but same length
• list: collection of elements, no restriction of content
• ...: classes for: DNA sequences, graphs, phylogenetic trees,
etc.

21/95
Introduction Basics Graphics Functions Modelling tools Getting fancy

Summary: basic object types

• integer: integer numbers


• numeric: decimal numbers
• character: character strings
• factor: categorical variables
• vector: collection of values (same type)
• matrix: collection of values (table, same type)
• [Link]: table where columns can have different types,
but same length
• list: collection of elements, no restriction of content
• ...: classes for: DNA sequences, graphs, phylogenetic trees,
etc.

21/95
Introduction Basics Graphics Functions Modelling tools Getting fancy

Summary: basic object types

• integer: integer numbers


• numeric: decimal numbers
• character: character strings
• factor: categorical variables
• vector: collection of values (same type)
• matrix: collection of values (table, same type)
• [Link]: table where columns can have different types,
but same length
• list: collection of elements, no restriction of content
• ...: classes for: DNA sequences, graphs, phylogenetic trees,
etc.

21/95
Introduction Basics Graphics Functions Modelling tools Getting fancy

Summary: basic object types

• integer: integer numbers


• numeric: decimal numbers
• character: character strings
• factor: categorical variables
• vector: collection of values (same type)
• matrix: collection of values (table, same type)
• [Link]: table where columns can have different types,
but same length
• list: collection of elements, no restriction of content
• ...: classes for: DNA sequences, graphs, phylogenetic trees,
etc.

21/95
Introduction Basics Graphics Functions Modelling tools Getting fancy

Summary: basic object types

• integer: integer numbers


• numeric: decimal numbers
• character: character strings
• factor: categorical variables
• vector: collection of values (same type)
• matrix: collection of values (table, same type)
• [Link]: table where columns can have different types,
but same length
• list: collection of elements, no restriction of content
• ...: classes for: DNA sequences, graphs, phylogenetic trees,
etc.

21/95
Introduction Basics Graphics Functions Modelling tools Getting fancy

Summary: basic object types

• integer: integer numbers


• numeric: decimal numbers
• character: character strings
• factor: categorical variables
• vector: collection of values (same type)
• matrix: collection of values (table, same type)
• [Link]: table where columns can have different types,
but same length
• list: collection of elements, no restriction of content
• ...: classes for: DNA sequences, graphs, phylogenetic trees,
etc.

21/95
Introduction Basics Graphics Functions Modelling tools Getting fancy

Summary: basic object types

• integer: integer numbers


• numeric: decimal numbers
• character: character strings
• factor: categorical variables
• vector: collection of values (same type)
• matrix: collection of values (table, same type)
• [Link]: table where columns can have different types,
but same length
• list: collection of elements, no restriction of content
• ...: classes for: DNA sequences, graphs, phylogenetic trees,
etc.

21/95
Introduction Basics Graphics Functions Modelling tools Getting fancy

Summary: basic object types

• integer: integer numbers


• numeric: decimal numbers
• character: character strings
• factor: categorical variables
• vector: collection of values (same type)
• matrix: collection of values (table, same type)
• [Link]: table where columns can have different types,
but same length
• list: collection of elements, no restriction of content
• ...: classes for: DNA sequences, graphs, phylogenetic trees,
etc.

21/95
Introduction Basics Graphics Functions Modelling tools Getting fancy

Summary: basic object types

• integer: integer numbers


• numeric: decimal numbers
• character: character strings
• factor: categorical variables
• vector: collection of values (same type)
• matrix: collection of values (table, same type)
• [Link]: table where columns can have different types,
but same length
• list: collection of elements, no restriction of content
• ...: classes for: DNA sequences, graphs, phylogenetic trees,
etc.

21/95
Introduction Basics Graphics Functions Modelling tools Getting fancy

Subsetting a vector: indices


Objects can be subsetted by index, name, or logical, using [] or
[[]]. Example using indices:
> x <- 10:1
> x

[1] 10 9 8 7 6 5 4 3 2 1

> x[c(1,2,5)]

[1] 10 9 6

> letters[2:10]

[1] "b" "c" "d" "e" "f" "g" "h" "i" "j"

> letters[-(1:20)]

[1] "u" "v" "w" "x" "y" "z"

22/95
Introduction Basics Graphics Functions Modelling tools Getting fancy

Subsetting a vector: logicals


x[foo] where foo is logical, returns the values of x where foo is
TRUE:
> x <- 1:10
> x < 5

[1] TRUE TRUE TRUE TRUE FALSE FALSE FALSE FALSE FALSE FALSE

> x[x<5]

[1] 1 2 3 4

> x[x %% 3 == 0]

[1] 3 6 9

23/95
Introduction Basics Graphics Functions Modelling tools Getting fancy

Subsetting a vector: names

x[foo] where x is named and foo is a vector of retained names:


> x <- sample(1:100, 10)
> names(x) <- letters[1:10]
> x

a b c d e f g h i j
44 74 72 42 22 5 96 36 95 50

> x[c("c","d","a","i")]

c d a i
72 42 44 95

24/95
Introduction Basics Graphics Functions Modelling tools Getting fancy

Subsetting and replacing values

x[foo] <- [Link] where x[foo] are values to be replaced


with [Link]:
> x <- round(rnorm(14),2)
> x

[1] 0.70 0.26 0.05 1.38 -0.42 0.75 0.68 0.02 -0.50 2.01
[11] -1.46 1.02 0.97 -0.40

> [Link] <- x


> [Link][[Link]<0] <- 0
> [Link]

[1] 0.70 0.26 0.05 1.38 0.00 0.75 0.68 0.02 0.00 2.01 0.00 1.02
[13] 0.97 0.00

25/95
Introduction Basics Graphics Functions Modelling tools Getting fancy

Subsetting matrices and data frames


Same principle, with x[lines, columns]:
> x <- matrix(1:15,nrow=3)
> x

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


[1,] 1 4 7 10 13
[2,] 2 5 8 11 14
[3,] 3 6 9 12 15

> x[c(3,1),]

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


[1,] 3 6 9 12 15
[2,] 1 4 7 10 13

> x[2,4:5]

[1] 11 14

> x[3,3]

[1] 9

26/95
Introduction Basics Graphics Functions Modelling tools Getting fancy

Subsetting lists
x[foo] to return a list, x[[foo]] for a single element:
> x <- list(a=rnorm(4), hi="Hello", stuff=letters[1:10]); x

$a
[1] -1.215042 1.867920 -2.428956 1.008787

$hi
[1] "Hello"

$stuff
[1] "a" "b" "c" "d" "e" "f" "g" "h" "i" "j"

> x[c(1,3)]

$a
[1] -1.215042 1.867920 -2.428956 1.008787

$stuff
[1] "a" "b" "c" "d" "e" "f" "g" "h" "i" "j"

> x[[3]]

[1] "a" "b" "c" "d" "e" "f" "g" "h" "i" "j"

> x$stuff
27/95
Introduction Basics Graphics Functions Modelling tools Getting fancy

Logical operations 1/4

> a <- c(TRUE,TRUE,FALSE,FALSE);


> b <- c(TRUE,FALSE,TRUE,FALSE)
> rbind(a,b)

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


a TRUE TRUE FALSE FALSE
b TRUE FALSE TRUE FALSE

> a & b # logical 'AND'

[1] TRUE FALSE FALSE FALSE

> a | b # logical 'OR'

[1] TRUE TRUE TRUE FALSE

28/95
Introduction Basics Graphics Functions Modelling tools Getting fancy

Logical operations 2/4

> !a # not A

[1] FALSE FALSE TRUE TRUE

> any(a) # at least one TRUE

[1] TRUE

> all(a) # all TRUE

[1] FALSE

> which(a) # indices of the TRUEs

[1] 1 2

29/95
Introduction Basics Graphics Functions Modelling tools Getting fancy

Logical operations 3/4

[Link] is useful to spot missing data (NAs)


> a <- c(3,NA,2,5,NA,10)
> [Link](a)

[1] FALSE TRUE FALSE FALSE TRUE FALSE

> a[![Link](a)]

[1] 3 2 5 10

30/95
Introduction Basics Graphics Functions Modelling tools Getting fancy

Logical operations 4/4

Logicals are numbers: TRUE=1, FALSE=0


> a <- -10:5
> sum(a>0)

[1] 5

> mean(a>0)

[1] 0.3125

> a * (a>0)

[1] 0 0 0 0 0 0 0 0 0 0 0 1 2 3 4 5

31/95
Introduction Basics Graphics Functions Modelling tools Getting fancy

Exercise: truncated normal distribution


Using rnorm, generate 1,000 values from N (µ = 1, σ = 3) and
truncate the distribution to retain stricly positive values. Derive
estimates of: E(X), V (X), p(X ≥ 3). The histogram (function
hist) should look like:
Truncated normal distribution (m=1,sd=3,x>0)

60
Frequency

40
20
0

0 2 4 6 8 10 12

32/95
Introduction Basics Graphics Functions Modelling tools Getting fancy

Exercise: truncated normal distribution


Solution:
> [Link](1)
> x <- rnorm(1000,1,3)
> x <- x[x>0]
> hist(x, col="grey",border="white", nclass=20,
+ main="Truncated normal distribution (m=1,sd=3,x>0)")

Truncated normal distribution (m=1,sd=3,x>0)


60
Frequency

40
20
0

0 2 4 6 8 10 12

33/95
Introduction Basics Graphics Functions Modelling tools Getting fancy

Exercise: truncated normal distribution

Solution (continued):
> mean(x)

[1] 2.835922

> var(x)

[1] 4.243519

> mean(x>=3)

[1] 0.4176

34/95
Introduction Basics Graphics Functions Modelling tools Getting fancy

Finding matches
a %in% b looks for matches of a in b and returns a logical:
> a <- c('b','z','a','f')
> b <- letters[1:10]
> b

[1] "a" "b" "c" "d" "e" "f" "g" "h" "i" "j"

> a %in% b

[1] TRUE FALSE TRUE TRUE

match(a,b) looks for matches of a in b and returns indices of the


matches:
> match(a,b)

[1] 2 NA 1 6

35/95
Introduction Basics Graphics Functions Modelling tools Getting fancy

Matching character strings using grep

grep implements character string matching:


> fields <- c("Age", "DateOnset", "Sex", "[Link]",
+ "dateofdeath", "Country")
> grep("date", fields, [Link]=TRUE)

[1] 2 4 5

> grep("date", fields, [Link]=TRUE, value=TRUE)

[1] "DateOnset" "[Link]" "dateofdeath"

36/95
Introduction Basics Graphics Functions Modelling tools Getting fancy

Exercise: estimating delay distributions of SARS


Load the dataset [Link] and using hist and summary,
characterize the delay distributions for i) onset to hospitalisation ii)
admission to discharge, and iii) onset to death.
> sars <- [Link]("[Link]", [Link]=c("","NA"))
> head(sars)

[Link] Admission Onset Discharge Death


1 HK0001 2003-02-22 2003-02-17 <NA> 2003-03-27
2 HK0002 2003-02-23 2003-02-17 <NA> <NA>
3 HK0003 2003-02-26 2003-02-17 2003-03-19 <NA>
4 HK0004 2003-02-28 2003-02-19 2003-03-22 <NA>
5 HK0005 2003-02-28 2003-02-20 2003-03-30 <NA>
6 HK0006 2003-03-02 2003-02-27 2003-03-24 <NA>
[Link]
1 4
2 3
3 4
4 4
5 4
6 4

> for(i in 2:5) sars[,i] <- [Link]([Link](sars[,i]))


> sars$Hospital <- factor(sars$[Link])
> range(sars$Onset)

[1] "2003-02-17" "2003-04-07"


37/95
Introduction Basics Graphics Functions Modelling tools Getting fancy

Exercise: estimating delay distributions of SARS


For onset to hospitalisation, you should get:
Onset to hospitalisation

250
200
150
Frequency

100
50
0

0 5 10 15

Days after onset

Min. 1st Qu. Median Mean 3rd Qu. Max.


0.00 2.00 3.00 3.68 5.00 15.00

38/95
Introduction Basics Graphics Functions Modelling tools Getting fancy

Exercise: estimating delay distributions of SARS


Solution, onset to hospitalisation:
> delay1 <- [Link](sars$Admission-sars$Onset)
> hist(delay1, col="royalblue", xlab="Days after onset",
+ main="Onset to hospitalisation")

Onset to hospitalisation

250
200
150
Frequency

100
50
0

0 5 10 15

Days after onset

> summary(delay1)

Min. 1st Qu. Median Mean 3rd Qu. Max.


0.00 2.00 3.00 3.68 5.00 15.00

39/95
Introduction Basics Graphics Functions Modelling tools Getting fancy

Exercise: estimating delay distributions of SARS


Solution, hospitalisation to discharge:
> delay2 <- [Link](sars$Discharge - sars$Admission)
> hist(delay2, col="salmon", xlab="Days after admission",
+ main="Hospitalisation to discharge")

Hospitalisation to discharge

25
20
15
Frequency

10
5
0

5 10 15 20 25 30 35

Days after admission

> summary(delay2)

Min. 1st Qu. Median Mean 3rd Qu. Max. NA's


5.00 12.00 16.00 16.43 20.00 33.00 1050

40/95
Introduction Basics Graphics Functions Modelling tools Getting fancy

Exercise: estimating delay distributions of SARS


Solution, onset to death:
> delay3 <- [Link](sars$Death - sars$Onset)
> hist(delay3, col="gold", xlab="Days after onset",
+ main="Onset to death")

Onset to death

7
6
5
Frequency

4
3
2
1
0

0 10 20 30 40

Days after onset

> summary(delay3)

Min. 1st Qu. Median Mean 3rd Qu. Max. NA's


4.00 10.00 14.00 15.68 20.75 38.00 1100

41/95
Introduction Basics Graphics Functions Modelling tools Getting fancy

Exercise: estimating delay distributions of SARS

Based on the delay of onset to death, what is the probability of


survival of a patient alive 20 days after onset?
> 1 - mean(delay3>20, [Link]=TRUE)

[1] 0.7272727

42/95
Introduction Basics Graphics Functions Modelling tools Getting fancy

Exercise: estimating delay distributions of SARS

Based on the delay of onset to death, what is the probability of


survival of a patient alive 20 days after onset?
> 1 - mean(delay3>20, [Link]=TRUE)

[1] 0.7272727

42/95
Introduction Basics Graphics Functions Modelling tools Getting fancy

Plan
Introduction
Basics
Types of objects
Basic object handling
Advanced object handling
Graphics
Basic graphics
ggplot2
Functions
Modelling tools
Linear models
Distributions
Optimization
Getting fancy
43/95
Introduction Basics Graphics Functions Modelling tools Getting fancy

The basic graphic system

The basic graphic system is organised in:


• high-level functions: plot, hist, barplot, dotchart, ...
• low-level functions: points, lines, axes, text, ...
• parameters: par(...)
44/95
Introduction Basics Graphics Functions Modelling tools Getting fancy

A toy example: Fisher’s iris


Let us use Fisher’s iris data:
> data(iris)
> class(iris)

[1] "[Link]"

> dim(iris)

[1] 150 5

> head(iris)

[Link] [Link] [Link] [Link] Species


1 5.1 3.5 1.4 0.2 setosa
2 4.9 3.0 1.4 0.2 setosa
3 4.7 3.2 1.3 0.2 setosa
4 4.6 3.1 1.5 0.2 setosa
5 5.0 3.6 1.4 0.2 setosa
6 5.4 3.9 1.7 0.4 setosa

45/95
Introduction Basics Graphics Functions Modelling tools Getting fancy

Basic scatterplot
> plot(iris$[Link], iris$[Link])

2.5
● ●●
● ●
●●●● ● ● ● ●
● ● ●
●●●● ● ●
2.0

●●●● ● ●
●● ● ●
●●
● ● ● ●● ● ● ●
● ●
● ● ● ●
iris$[Link]

1.5

● ●●● ●●●
● ● ●●● ●
● ● ● ●●
●●●●●
●● ● ● ●
● ●●
1.0

● ● ● ●●


0.5


● ●●● ●
●●● ●
● ●●
● ● ●●
●●
●●●● ●
● ●●

1 2 3 4 5 6 7

iris$[Link]

See ?plot, ?[Link] and par for customisation.


46/95
Introduction Basics Graphics Functions Modelling tools Getting fancy

Changing titles and axis labels


> plot(iris$[Link], iris$[Link],
+ main="Iris data - petal length vs petal width",
+ xlab="Petal length", ylab="Petal width")

Iris data − petal length vs petal width


2.5

● ●●
● ●
●●●● ● ● ● ●
● ● ●
●●●● ● ●
2.0

●●●● ● ●
●● ● ●
●●
● ● ● ●● ● ● ●
● ●
● ● ● ●
1.5

● ●●● ●●●
Petal width

● ● ●●● ●
● ● ● ●●
●●●●●
●● ● ● ●
● ●●
1.0

● ● ● ●●


0.5


● ●●● ●
●●● ●
● ●●
● ● ●●
●●
●●●● ●
● ●●

1 2 3 4 5 6 7

Petal length

47/95
Introduction Basics Graphics Functions Modelling tools Getting fancy

Adding color
> col <- iris$Species;levels(col)

[1] "setosa" "versicolor" "virginica"

> levels(col) <- c("royalblue","red3","gold")


> col <- [Link](col)
> plot(iris$[Link], iris$[Link], col=col)
> title("Iris data - petal length vs petal width")

Iris data − petal length vs petal width


2.5

● ●●
● ●
●●●● ● ● ● ●
● ● ●
●●●● ● ●
2.0

●●●● ● ●
●● ● ●
●●
● ● ● ●● ● ● ●
● ●
● ● ● ●
iris$[Link]

1.5

● ●●● ●●●
● ● ●●● ●
● ● ● ●●
●●●●●
●● ● ● ●
● ●●
1.0

● ● ● ●●


0.5


● ●●● ●
●●● ●
● ●●
● ● ●●
●●
●●●● ●
● ●●

1 2 3 4 5 6 7

iris$[Link]

48/95
Introduction Basics Graphics Functions Modelling tools Getting fancy

Changing symbols
Exercise: using the same trick as for color, use different symbols
for the species:
Iris data − petal length vs petal width

2.5
● ● ●

● ●

● ● ● ● ● ● ● ●

● ● ●

● ● ● ● ● ●
2.0

● ● ● ● ● ●

● ● ● ●

● ● ● ● ● ● ● ●


iris$[Link]

1.5

● ●


1.0
0.5

1 2 3 4 5 6 7

iris$[Link]

49/95
Introduction Basics Graphics Functions Modelling tools Getting fancy

Note: to choose your symbols...


> plot(0:20, rep(0,21), pch=0:20, cex=3,
+ xlab="pch = ...", yaxt="n", ylab="")
> abline(v=seq(0,20,by=5), col="grey", lty=2)

● ● ● ● ●●

0 5 10 15 20

pch = ...

50/95
Introduction Basics Graphics Functions Modelling tools Getting fancy

Changing symbols
Solution:
> symb <- iris$Species
> levels(symb) <- c(4, 5, 20)
> symb <- [Link]([Link](symb))
> plot(iris$[Link], iris$[Link], pch=symb, col=col)
> title("Iris data - petal length vs petal width")

Iris data − petal length vs petal width


2.5

● ● ●

● ●

● ● ● ● ● ● ● ●

● ● ●

● ● ● ● ● ●
2.0

● ● ● ● ● ●

● ● ● ●

● ● ● ● ● ● ● ●


iris$[Link]

1.5

● ●


1.0
0.5

1 2 3 4 5 6 7

iris$[Link] 51/95
Introduction Basics Graphics Functions Modelling tools Getting fancy

Adding a legend
> plot(iris$[Link], iris$[Link], pch=symb, col=col)
> title("Iris data - petal length vs petal width")
> legend("bottomright", col=c("royalblue","red3","gold"),
+ pch=c(4, 5, 20), leg=levels(iris$Species))

Iris data − petal length vs petal width


2.5
● ● ●

● ●

● ● ● ● ● ● ● ●

● ● ●

● ● ● ● ● ●
2.0

● ● ● ● ● ●

● ● ● ●

● ● ● ● ● ● ● ●


iris$[Link]

1.5

● ●


1.0
0.5

setosa
versicolor

virginica

1 2 3 4 5 6 7

iris$[Link]

52/95
Introduction Basics Graphics Functions Modelling tools Getting fancy

Looking for all biplots


pairs is useful for a quick visualisation of all possible scatterplots
in a dataset:
> pairs(iris[,-5], col=col, pch=symb)

2.0 2.5 3.0 3.5 4.0 0.5 1.0 1.5 2.0 2.5

● ● ●
● ● ● ● ● ●● ● ●●

7.5
● ● ●
● ● ●
● ● ●
● ● ● ● ●● ● ● ●
● ● ●
●● ● ● ● ● ●
● ● ● ● ● ●
● ●● ● ● ●●● ● ● ●●●

6.5
● ● ●● ● ● ● ● ●
●● ●● ● ●● ●● ●●●

[Link]
● ●●● ●● ●●● ● ● ● ●● ●●
● ● ● ● ● ●
● ● ● ● ● ●
● ● ●● ● ●
● ● ●
●● ● ● ●
● ● ●

5.5
● ● ●

● ● ●

4.5
2.0 2.5 3.0 3.5 4.0

● ● ● ● ● ●

● ● ●

●● ●● ●●

●●●
● ●
●● ●● ●
● ● ●
● ●● ●● ●●
[Link] ● ●●●
● ●
● ● ● ●●

●● ●● ● ●● ● ● ●
● ●



● ●●
● ●●●●

● ● ● ● ●
● ● ●●● ● ● ●● ● ● ● ● ● ●●●●● ●
● ●● ●●● ●●
● ● ● ● ● ●
● ● ● ● ● ● ● ●●●●

● ● ●

7
● ● ●
●● ● ● ● ●●●
● ● ● ● ● ●
● ● ● ● ● ● ●● ● ● ●

6
● ● ●● ● ●
● ●●● ●● ● ● ●
● ● ● ●●
● ●
● ●● ● ● ●●●● ●●●● ● ● ● ● ●
●● ●
● ●● ●● ● ●● ● ●
● ● ● ●
●● ● ● ●
● ● ● ● ●● ●
● ● ●●● ● ●● ● ●●

5
●● ● ●
●●●●
● ●● ●
● ●
● ● ●
● ●
● ● ●

[Link]

4
3
2
1
0.5 1.0 1.5 2.0 2.5

● ● ● ● ● ● ●●
● ● ● ● ● ● ● ●
● ● ●●● ● ● ●●● ● ●●●● ● ● ● ●
●● ● ● ● ● ●● ●
● ●●● ● ● ● ●● ● ●●●● ● ●
●● ● ● ● ● ● ● ● ● ●●●● ● ●
● ●● ● ● ●● ●● ● ●
●●●●●●● ● ●● ● ●●●●●● ●● ● ●● ● ● ●
● ● ●
● ● ●
● ● ● ● ●●

[Link]
● ● ●

4.5 5.5 6.5 7.5 1 2 3 4 5 6 7

53/95
Introduction Basics Graphics Functions Modelling tools Getting fancy

ggplot2 : a grammar for graphics

A separate graphics system:


• designed for data stored as [Link]
• graphics are objects
• different components of the graphisc added using ‘+’
• geoms: types of graphics
• aesthetics: mapping data to visual properties
• user specifies aesthetics, not technical details
• not compatible with basic graphics

Documentation: [Link]/current/

54/95
Introduction Basics Graphics Functions Modelling tools Getting fancy

ggplot2 : a grammar for graphics

A separate graphics system:


• designed for data stored as [Link]
• graphics are objects
• different components of the graphisc added using ‘+’
• geoms: types of graphics
• aesthetics: mapping data to visual properties
• user specifies aesthetics, not technical details
• not compatible with basic graphics

Documentation: [Link]/current/

54/95
Introduction Basics Graphics Functions Modelling tools Getting fancy

ggplot2 : a grammar for graphics

A separate graphics system:


• designed for data stored as [Link]
• graphics are objects
• different components of the graphisc added using ‘+’
• geoms: types of graphics
• aesthetics: mapping data to visual properties
• user specifies aesthetics, not technical details
• not compatible with basic graphics

Documentation: [Link]/current/

54/95
Introduction Basics Graphics Functions Modelling tools Getting fancy

ggplot2 : a grammar for graphics

A separate graphics system:


• designed for data stored as [Link]
• graphics are objects
• different components of the graphisc added using ‘+’
• geoms: types of graphics
• aesthetics: mapping data to visual properties
• user specifies aesthetics, not technical details
• not compatible with basic graphics

Documentation: [Link]/current/

54/95
Introduction Basics Graphics Functions Modelling tools Getting fancy

ggplot2 : a grammar for graphics

A separate graphics system:


• designed for data stored as [Link]
• graphics are objects
• different components of the graphisc added using ‘+’
• geoms: types of graphics
• aesthetics: mapping data to visual properties
• user specifies aesthetics, not technical details
• not compatible with basic graphics

Documentation: [Link]/current/

54/95
Introduction Basics Graphics Functions Modelling tools Getting fancy

ggplot2 : a grammar for graphics

A separate graphics system:


• designed for data stored as [Link]
• graphics are objects
• different components of the graphisc added using ‘+’
• geoms: types of graphics
• aesthetics: mapping data to visual properties
• user specifies aesthetics, not technical details
• not compatible with basic graphics

Documentation: [Link]/current/

54/95
Introduction Basics Graphics Functions Modelling tools Getting fancy

ggplot2 : a grammar for graphics

A separate graphics system:


• designed for data stored as [Link]
• graphics are objects
• different components of the graphisc added using ‘+’
• geoms: types of graphics
• aesthetics: mapping data to visual properties
• user specifies aesthetics, not technical details
• not compatible with basic graphics

Documentation: [Link]/current/

54/95
Introduction Basics Graphics Functions Modelling tools Getting fancy

ggplot2 : simple example


> library(ggplot2)
> base <- ggplot(data=iris, aes(x=[Link], y=[Link]))
> p <- base + geom_point()
> p

2.5 ● ●●

● ●

●●●● ● ● ● ●

● ● ●

●●●● ● ●

2.0 ●●●● ● ●

●● ● ●

●● ● ●● ● ● ●

● ●

● ● ● ●

1.5 ● ●●● ●●●


[Link]

● ● ●●● ●

● ●●●●●●●

●● ● ● ●

● ●●

1.0 ● ● ● ●●

0.5 ●

● ●●● ●

●●● ●

● ●●●●●● ●

● ●●

0.0
2 4 6
[Link]

55/95
Introduction Basics Graphics Functions Modelling tools Getting fancy

ggplot2 : changing colors and symbols


> p <- p + aes(colour=Species, shape=Species)
> p

2.5

2.0

1.5
Species
[Link]

● setosa
versicolor
virginica

1.0

0.5 ●

● ●●● ●

●●● ●

● ●●●●●● ●

● ●●

0.0
2 4 6
[Link]

56/95
Introduction Basics Graphics Functions Modelling tools Getting fancy

ggplot2 : aes within geom


> p <- base + geom_point(aes(colour=Species, shape=Species))
> p

2.5

2.0

1.5
Species
[Link]

● setosa
versicolor
virginica

1.0

0.5 ●

● ●●● ●

●●● ●

● ●●●●●● ●

● ●●

0.0
2 4 6
[Link]

57/95
Introduction Basics Graphics Functions Modelling tools Getting fancy

ggplot2 : aes versus standard parameters


> p <- base + geom_point(aes(colour=Species, shape=Species),
+ size=10, alpha=.4)
> p

2.5

2.0

Species
1.5
[Link]

setosa

versicolor

virginica
1.0

0.5

0.0
2 4 6
[Link]

58/95
Introduction Basics Graphics Functions Modelling tools Getting fancy

ggplot2 : changing labels


> p + labs(x="Petal length (cm)", y="Petal width (cm)",
+ title="Fisher's Iris data")

Fisher's Iris data


2.5

2.0

Species
Petal width (cm)

1.5
setosa

versicolor

virginica
1.0

0.5

0.0
2 4 6
Petal length (cm)

59/95
Introduction Basics Graphics Functions Modelling tools Getting fancy

ggplot2 : application to time series


Exercise: load the dataset [Link] and derive an incidence curve
using geom histogram
> sars <- [Link]("[Link]", [Link]=c("","NA"))
> head(sars)

[Link] Admission Onset Discharge Death


1 HK0001 2003-02-22 2003-02-17 <NA> 2003-03-27
2 HK0002 2003-02-23 2003-02-17 <NA> <NA>
3 HK0003 2003-02-26 2003-02-17 2003-03-19 <NA>
4 HK0004 2003-02-28 2003-02-19 2003-03-22 <NA>
5 HK0005 2003-02-28 2003-02-20 2003-03-30 <NA>
6 HK0006 2003-03-02 2003-02-27 2003-03-24 <NA>
[Link]
1 4
2 3
3 4
4 4
5 4
6 4

> for(i in 2:5) sars[,i] <- [Link]([Link](sars[,i]))


> sars$Hospital <- factor(sars$[Link])
> range(sars$Onset)

[1] "2003-02-17" "2003-04-07"

60/95
Introduction Basics Graphics Functions Modelling tools Getting fancy

ggplot2 : application to time series

Exercise: load the dataset [Link] and derive an incidence curve


using geom histogram

100
Weekly incidence

Hospital
1
2
3
4
50

Feb 15 Mar 01 Mar 15 Apr 01


Date of onset

61/95
Introduction Basics Graphics Functions Modelling tools Getting fancy

ggplot2 : application to time series


Solution:
> p <- ggplot(sars) +
+ geom_histogram(aes(x=Onset, fill=Hospital)) +
+ labs(x="Date of onset", y="Weekly incidence")
> p

100
Weekly incidence

Hospital
1
2
3
4
50

Feb 15 Mar 01 Mar 15 Apr 01


Date of onset

62/95
Introduction Basics Graphics Functions Modelling tools Getting fancy

ggplot2 : facetting
Exercise: using facet grid(rows ∼ columns), create the
multi-panel figure below:
40

1
20

40

2
Weekly incidence

20
Hospital
1
0 2
3

40 4

3
20

40

4
20

0
Feb 15 Mar 01 Mar 15 Apr 01
Date of onset

63/95
Introduction Basics Graphics Functions Modelling tools Getting fancy

ggplot2 : facetting
Solution:
> p + facet_grid(Hospital ~ .)

40

1
20

40

2
Weekly incidence

20
Hospital
1
0 2
3

40 4

3
20

40

4
20

0
Feb 15 Mar 01 Mar 15 Apr 01
Date of onset

64/95
Introduction Basics Graphics Functions Modelling tools Getting fancy

Plan
Introduction
Basics
Types of objects
Basic object handling
Advanced object handling
Graphics
Basic graphics
ggplot2
Functions
Modelling tools
Linear models
Distributions
Optimization
Getting fancy
65/95
Introduction Basics Graphics Functions Modelling tools Getting fancy

A simple example

Functions are declared using:


> foo <- function(x){
+ ## do stuff with x here
+ x <- x+1

+ ## return result
+ return(x)
+ }
>
> foo(9)

[1] 10

> foo([Link]("2001-01-01"))

[1] "2001-01-02"

66/95
Introduction Basics Graphics Functions Modelling tools Getting fancy

Functions and scope 1/2

Each function has its own temporary environment; objects created


during the call to the function disappear after the call:
> foo <- function(x){
+ temp <- 1
+ x <- x+temp
+ return(x)
+ }
>
> x <- 9
> foo(x)

[1] 10

> temp

Error in eval(expr, envir, enclos): object ’temp’ not found

67/95
Introduction Basics Graphics Functions Modelling tools Getting fancy

Functions and scope 2/2


Objects are searched in the current environment; if not found,
looks recursively in the surrounding environments:
> temp <- 1000
> foo <- function(x){
+ x <- x+temp
+ temp <- temp-1
+ return(x)
+ }
>
> x <- 9
> foo(x)

[1] 1009

> temp

[1] 1000

> x

[1] 9

68/95
Introduction Basics Graphics Functions Modelling tools Getting fancy

Functions can be plotted


Function which have a scalar for input and output can be plotted:
> a <- function(x) sin(x)*pi
> plot(a, xlim=c(0,12))

3
2
1
a

0
−1
−2
−3

0 2 4 6 8 10 12

69/95
Introduction Basics Graphics Functions Modelling tools Getting fancy

Plan
Introduction
Basics
Types of objects
Basic object handling
Advanced object handling
Graphics
Basic graphics
ggplot2
Functions
Modelling tools
Linear models
Distributions
Optimization
Getting fancy
70/95
Introduction Basics Graphics Functions Modelling tools Getting fancy

Linear regression

Aim: predict response variable y as a linear function of x. The


problem is to estimate the intercept β0 and the slope β1 in:

yi = β0 + β1 xi + i

where typically i ∼ N (0, σ ).

71/95
Introduction Basics Graphics Functions Modelling tools Getting fancy

Linear regression using Fisher’s iris


> plot(iris$[Link], iris$[Link])
> title("Iris data - petal length vs petal width")

Iris data − petal length vs petal width

2.5
● ●●
● ●
●●●● ● ● ● ●
● ● ●
●●●● ● ●
2.0

●●●● ● ●
●● ● ●
●●
● ● ● ●● ● ● ●
● ●
● ● ● ●
iris$[Link]

1.5

● ●●● ●●●
● ● ●●● ●
● ● ● ●●
●●●●●
●● ● ● ●
● ●●
1.0

● ● ● ●●


0.5


● ●●● ●
●●● ●
● ●●
● ● ●●
●●
●●●● ●
● ●●

1 2 3 4 5 6 7

iris$[Link]

How can we predict with petal width using petal length?


72/95
Introduction Basics Graphics Functions Modelling tools Getting fancy

The function lm

The model is written as a formula: lm(y ~


x):
> lm1 <- lm([Link] ~ [Link], data=iris)
> lm1

Call:
lm(formula = [Link] ~ [Link], data = iris)

Coefficients:
(Intercept) [Link]
-0.3631 0.4158

73/95
Introduction Basics Graphics Functions Modelling tools Getting fancy

Plotting a linear regression


abline can be used to add the curve of a linear regression:
> plot(iris$[Link], iris$[Link])
> title("Iris data - petal length vs petal width")
> abline(lm1, col="blue")

2.5 Iris data − petal length vs petal width

● ●●
● ●
●●●● ● ● ● ●
● ● ●
●●●● ● ●
2.0

●●●● ● ●
●● ● ●
●●
● ● ● ●● ● ● ●
● ●
● ● ● ●
iris$[Link]

1.5

● ●●● ●●●
● ● ●●● ●
● ● ● ●●
●●●●●
●● ● ● ●
● ●●
1.0

● ● ● ●●


0.5


● ●●● ●
●●● ●
● ●●
● ● ●●
●●
●●●● ●
● ●●

1 2 3 4 5 6 7

iris$[Link]

74/95
Introduction Basics Graphics Functions Modelling tools Getting fancy

Linear modelling goes beyong regression

• lm: allows predictors, categorical or numeric


• glm: generalized linear models (binomial, Poisson, etc.)
• anova: model comparison (lm or glm)
• nlme: package for non-linear mixed effect models
• splines: package for splines

See: “The R book” by Crawley (2012), Wiley.

75/95
Introduction Basics Graphics Functions Modelling tools Getting fancy

Random variable distributions

In , they typically are implemented by 4 functions; e.g. for the


normal distribution:
• dnorm: probability density function
• pnorm: cumulative distribution function (p-value)
• qnorm: quantile function
• rnorm: generate Normal random variates

76/95
Introduction Basics Graphics Functions Modelling tools Getting fancy

Probability density function

> plot(dnorm, xlim=c(-4,4), ylab="p(X)")

0.4
0.3
p(X)

0.2
0.1
0.0

−4 −2 0 2 4

77/95
Introduction Basics Graphics Functions Modelling tools Getting fancy

Cumulative distribution

> plot(pnorm, xlim=c(-4,4), ylab="p(X>=x)")

1.0
0.8
0.6
p(X>=x)

0.4
0.2
0.0

−4 −2 0 2 4

78/95
Introduction Basics Graphics Functions Modelling tools Getting fancy

Quantile distribution

> plot(qnorm, xlim=0:1, xlab="quantile", ylab="value of X")

2
1
value of X

0
−1
−2

0.0 0.2 0.4 0.6 0.8 1.0

quantile

79/95
Introduction Basics Graphics Functions Modelling tools Getting fancy

Random variate
> x <- rnorm(1000)
> head(x,5)

[1] 1.13496509 1.11193185 -0.87077763 0.21073159 0.06939565

> hist(x, nclass=30, col="grey",border="white",prob=TRUE)


> plot(dnorm, add=TRUE, xlim=c(-4,4), lty=2)

Histogram of x
0.4
0.3
Density

0.2
0.1
0.0

−3 −2 −1 0 1 2 3 4

x 80/95
Introduction Basics Graphics Functions Modelling tools Getting fancy

Other distributions
Similar functions exist for a range of distributions:
• runif: uniform distribution
• rpois: Poisson
• rbinom: binomial
• rgamma: gamma
• rbeta: beta
• rchisq: χ2
• rexp: exponential
• rgeom: geometric
• rcauchy: Cauchy
• mvrnorm: multivariate Normal
See dedicated task view: [Link]/web/views.
81/95
Introduction Basics Graphics Functions Modelling tools Getting fancy

The function optim


Optimization (minimization) of a function. Let us define a weird
mixture of gamma and Normal distribution:
> weird <- function(x) {
+ out <- dgamma(x, rate=.5, shape=1.5) - dnorm(x)
+ return(out)
+ }
> plot(weird, xlim=c(0,10))
0.1
0.0
−0.1
weird

−0.2
−0.3
−0.4

0 2 4 6 8 10

x 82/95
Introduction Basics Graphics Functions Modelling tools Getting fancy

The function optim

> res <- optim(0, function(x) -weird(x))


> res$par

[1] 2.394531

> res$value

[1] -0.1637565

83/95
Introduction Basics Graphics Functions Modelling tools Getting fancy

The function optim


> plot(weird, xlim=c(0,10))
> segments(res$par,-.5,res$par,-res$value,col="red")
> segments(-.5,-res$value,res$par,-res$value,col="red")
> points(res$par,-res$value,cex=2,col="red")


0.1
0.0
−0.1
weird

−0.2
−0.3
−0.4

0 2 4 6 8 10

84/95
Introduction Basics Graphics Functions Modelling tools Getting fancy

Linear regression: least squares or maximum-likelihood?


> coef(lm1)

(Intercept) [Link]
-0.3630755 0.4157554

Iris data − petal length vs petal width


2.5


observed ● ● ●

predicted ● ●

● ● ● ● ● ● ● ●

● ● ●

● ● ● ● ● ●
2.0

● ● ● ● ● ●

● ● ● ●

● ● ● ● ● ● ● ●

● ●

● ● ● ●
1.5

● ● ● ● ● ● ●
Petal width

● ● ● ● ● ●

● ● ● ● ● ● ● ●

● ● ● ● ●

● ● ●
1.0

● ● ● ● ●


0.5

● ● ● ● ●

● ● ● ●

● ● ● ● ● ● ● ●

● ● ●

1 2 3 4 5 6 7

Petal length

85/95
Introduction Basics Graphics Functions Modelling tools Getting fancy

Estimation using least squares

> [Link] <- function(y,x){


+ sumsq <- function(param){ # param = c(a,b)
+ return(sum((y - (param[1] + param[2]*x))^2))
+ }
+ return(optim(c(0,0), sumsq))
+ }
>
> [Link](iris$[Link],iris$[Link])$par

[1] -0.3630889 0.4157252

86/95
Introduction Basics Graphics Functions Modelling tools Getting fancy

Estimation using maximum likelihood

> [Link] <- function(y,x){


+ deviance <- function(param){ # param = c(a,b)
+ resid <- y - (param[1] + param[2]*x)
+ dev <- sum(-dnorm(resid,0,sd(resid),log=TRUE))
+ return(dev)
+ }
+ return(optim(c(0,0), deviance))
+ }
>
> [Link](iris$[Link],iris$[Link])$par

[1] -0.3630421 0.4157455

87/95
Introduction Basics Graphics Functions Modelling tools Getting fancy

Plan
Introduction
Basics
Types of objects
Basic object handling
Advanced object handling
Graphics
Basic graphics
ggplot2
Functions
Modelling tools
Linear models
Distributions
Optimization
Getting fancy
88/95
Introduction Basics Graphics Functions Modelling tools Getting fancy

Using vectorised functions 1/4


> m <- runif(1e6, 1, 10)
> x <- rnorm(1e6, mean=m)
> hist(x, col="grey", border="white")

Histogram of x

1e+05
8e+04
6e+04
Frequency

4e+04
2e+04
0e+00

0 5 10 15

Let us compute the likelihood of this distribution.


89/95
Introduction Basics Graphics Functions Modelling tools Getting fancy

Using vectorised functions 2/4


Using a for loop:
> [Link]({
+ ll1 <- 0
+ for(i in 1:1e6){
+ ll1 <- ll1 + dnorm(x[i], mean=m[i],log=TRUE)
+ }
+ }
+ )

user system elapsed


3.871 0.000 3.921

> ll1

[1] -1418994

90/95
Introduction Basics Graphics Functions Modelling tools Getting fancy

Using vectorised functions 3/4

Using a sapply:
> [Link](
+ ll2 <- sum(sapply(1:1e6, function(i) dnorm(x[i], mean=m[i], log=TRUE)))
+ )

user system elapsed


6.198 0.026 6.333

> ll2

[1] -1418994

91/95
Introduction Basics Graphics Functions Modelling tools Getting fancy

Using vectorised functions 4/4

Using native vectorisation:


> [Link](ll3 <- sum(dnorm(x, mean=m, log=TRUE)))

user system elapsed


0.077 0.000 0.076

> ll3

[1] -1418994

92/95
Introduction Basics Graphics Functions Modelling tools Getting fancy

Literate programming

• Aim: generate automated documents including inputs and


outputs of a program.
• Sweave: literate programing LATEX +
• knitr: literate programing LATEX + (improves Sweave),
and Markdown +

93/95
Introduction Basics Graphics Functions Modelling tools Getting fancy

Sweave vs knitr
Sweave
Sweave pdf latex
• compilation: [Link] −
−−−−→ [Link] −−−−−→ [Link]
• chunks of code embedded in LATEXdocument
• needs specific headers to compile
• limited options

knitr
knit2pdf
• compilation: [Link] −−−−−→ [Link]
• syntax nearly identical to Sweave
• syntax highlighting
• very flexible, simpler

See: [Link]
94/95
Introduction Basics Graphics Functions Modelling tools Getting fancy

To conclude

Lots of resources:
• ’s official website: [Link]/
• mailing lists: [Link]/[Link]
• task views: [Link]/web/views/
• The -epi project:
[Link]/site/therepiproject/
• The book by Crawley (2012), Wiley.

95/95

You might also like