Introduction to R Laurent Ferrara Summer School in Quantitative Finance - July 2008
Plan
Objective
Why R ? I
R is the open source version of S-Plus
I
Both are written in S language
I
R is FREE !!!
I
R is reliable
I
R allows many kinds of statistical and econometric analysis
I
R is object-oriented
R Installation
Procedure I
Go to the R-project web site: http://www.r-project.org/
I
Go to: Download / CRAN (left column)
I
Go to the nearest mirror site (France: Toulouse, URL: cran.cict.fr)
I
Go to: Download and install R (with Windows)
I
You will arrive on this link : http://cran.cict.fr/bin/windows/base/R-2.5.1-win32.exe
I
Lauch the .exe file
Package Installation (Example: tseries) Procedure I
Go to the nearest mirror site (France: Toulouse, URL: cran.cict.fr)
I
Go to Software/Packages (left column)
I
Click on tseries in the list of contributed packages
I
Download the .zip file (exe) and the .pdf file (manual)
I
Repeat the previous steps for the packages zoo and quadprog (needeed to run tseries)
I
Go back to R, from the toolbar go to Packages/Install packages from the zip files and select the right package
I
From the toolbar, go to Packages/Charge the package and select tseries
I
To verify that it is correctly installed type: > help(arma)
First steps with R
I
Double-click on the icon
I
Information on R appear
I
The symbol > indicates that you can write lines of commands
I
The symbol + indicates that your line of command is not finished
I
R is case-sensitive
I
to quit R: > q()
I
Don’t forget to save an image of your workspace so that you can find your objects next time you will open this workspace
Basic operations with R
I
Symbols + - / * allow classical operations > 2+3 5 > 2*3 6 > 2**3 8
I
Affectation > x=2+3 > x 5
R Objects
I
vector
I
matrix
I
array
I
data.frame
I
list
I
ts
Vector Several ways to create vectors I
Concatenation by c() > x=c(1,3,5) > x 1 3 5 > y=c(2,4,6) > z=c(1,y) > z 1 2 4 6
I
Sequence > 1:6 1 2 3 4 5 6 > 1.5:6 1.5 2.5 3.5 4.5 5.5 > seq(1,6) 1 2 3 4 5 6
Vector
I
Sequence > seq(1,6,by=2) 1 3 5
I
Repeat > rep(1,4) 1 1 1 1
I
Sub-vector > x[2] 3 > x[2:3] 3 5
Vector I
I
I
I
Sub-vector > x[2] 3 > x[2:3] 3 5 Sub-vector with conditions > vect=1:10 > vect[vect>6] > vect[(vect>6) | (vect vect[(vect>6) | (vect x+y 3 7 11 > x+z 2 5 9 7 Warning: cyclical completion
Matrix
I
Creation from a vector by matrix() > Xmat=matrix(c(1,3,5,7,9,11),nrow=3) > matrix(c(1,3,5,7,9,11),ncol=3) > matrix(c(1,3,5,7,9,11),nrow=3,byrow=T)
I
Sub-matrix > Xmat[,1] 3 7 11 > Xmat[2,] 5 7 > Xmat[2:3,] 5 7 9 11
> > > > > 1
matrix(c(1,3,5,7,9,11),ncol=3) matrix(c(1,3,5,7,9,11),nrow=3,byrow=T) y=c(2,4,6) z=c(1,y) z 2 4 6