1
R1: Get started
http://www.r-project.org/other-docs.html http://tolstoy.newcastle.edu.au/R/
http://devcheatsheet.com/tag/r/
http://www.mayin.org/ajayshah/KB/R/
http://www.rexamples.com/
2
Starting R
• Start R:
➢ Type in terminal/console: R
➢ Type q() to close the GUI
➢ Use setwd(directory) to change your working directory. Or set up from File menu.
➢ Command history saved in: .Rhistory
● Use save.image() to save your varibles in: .Rdata
➢ Remember to comment your program by #
• Current varialbes:
➢ Display current variables: ls()
➢ Clear variables: rm(Variable_Name), rm(list=ls())
3
Get help
●Type Help(), help.start(), your will get a bounch of help topics. Select the topic your are looking for.
●If you know your function. Type help ('Function_Name')
R documents/mailing list:
http://www.r-project.org/other-docs.html http://tolstoy.newcastle.edu.au/R/
Short reference card:
http://devcheatsheet.com/tag/r/
Examples:
http://www.mayin.org/ajayshah/KB/R/
http://www.rexamples.com/
4
Mathematical functions
> a<-1
> b<-10
> c<- -2
> d <- a*b + c
> d [1] 8
> d <- b/c
> d [1] -5
● You can only assign one variable at one line, which is different from Matlab.
● Usíng <- for assignment
5
R 2: Plot
http://www.harding.edu/fmccown/r/
6
Simple Plot
> x <- seq(from = 0, to = 2*pi, by =pi/100)
> # x is a sequence from 0 to 2*pi, step by pi/100
> y <- sin(x)
> png(filename="sinplot.png")
> #save your plot in sinplot.png
> plot(x,y,
+ xlab="x:0 : 2*pi",ylab="sin(x)", + main="Sin function")
> #add labels and title
7
Multiple data sets in one plot
Plot Sine and Cosine in one plot:
> x <- seq(from = 0, to = 2*pi, by =pi/100)
> y1 <- sin(x)
> y2 <- cos(x)
> plot(x,y1, xlab="x:0 : 2*pi",ylab="sin(x)/Cos(x)", + main="Sin/Cos function",col="black",type='l')
> # plot y1 vs x
> lines(x,y2,col="red",type='l')
> # add y2 to the plot
> legend("topright",lty=1,l
+ egend = c("sin(x)", "cos(x)"),col=c("black","red"))
> # add legend
8
Multiple data sets in one plot
Plot Sine and Cosine in one plot:
> x <- seq(from = 0, to = 2*pi, by =pi/100)
> y1 <- sin(x)
> y2 <- cos(x)
> plot(x,y1, xlab="x:0 : 2*pi",ylab="sin(x)/Cos(x)", + main="Sin/Cos function",col="black",type='l')
> # plot y1 vs x
> lines(x,y2,col="red",type='l')
> # add y2 to the plot
> legend("topright",lty=1,l
+ egend = c("sin(x)", "cos(x)"),col=c("black","red"))
> # add legend
9
10
Subplot
Plot Sine and Cosine in two rows:
> par(mfrow=c(2,1))
> # split plot window to two rows
> plot(x,y1,
+ xlab="x:0 : 2*pi",ylab="sin(x)", + main="Sin function",type='l')
> plot(x,y2,
+ xlab="x:0 : 2*pi",ylab="Cos(x)", + main="Cos function",type='l')
11
R 3: Matrices
http://www.ats.ucla.edu/stat/r/library/matrix_alg.htm
12
Construct Vectors
●Define a vector of c(1,2,3,4,5,6) by 3 methods:
> vector1 <- c(1,2,3,4,5,6)
> vector1
[1] 1 2 3 4 5 6
> vector2 <- c(1:6)
> vector2
[1] 1 2 3 4 5 6
> vector3 <- seq(1,6,by=6)
> vector3 [1] 1
●Sub vectors:
> # find all numbers >3 in vector1
> vector1[vector1>3]
[1] 4 5 6
13
Construct Matrices
●Define a matrix with 3 rows and 2 columns
> Matrix1 <- matrix( c(1, 2, 3, 4, 5, 6), nrow=3, ncol=2)
> Matrix1 [,1] [,2]
[1,] 1 4 [2,] 2 5 [3,] 3 6
●Sub matrix:
> Matrix1[1,] # row 1 of Matrix1 [1] 1 4
> Matrix1[c(1,2),2]
> # row 1 and 2 and column 2 of Matrix1 [1] 4 5
15
Matrix Operation 2
> a <- matrix(c(1:4), nrow=2, ncol=2)
> b <- matrix(c(2,2,2,2), nrow=2, ncol=2)
The dimension of matrix must be agree to do matrix operation Matrix operation is defined by %*%, %/%, ^
> c <- a%*%b #matrix multiplication
> c
[,1] [,2]
[1,] 8 8 [2,] 12 12
If you want to do element by element operation, just use the sign without % around.
> a*b #dot multiplication [,1] [,2]
[1,] 2 6 [2,] 4 8
16
Matrix operation 3
Inverse of matrix is solve(Matrix). Then we can calculate b by:
> solve(a)%*%c [,1] [,2]
[1,] 2 2 [2,] 2 2 Or by
> solve(a, c) [,1] [,2]
[1,] 2 2 [2,] 2 2
17
Data Frame
A dataframe is an important R structure.It use the rows as observations and the columns as variables. It is required by many build-in R functions.
> a <- c(7:9)
> b <- c(4:6)
> d <- data.frame(a=a,b=b)
> d a b 1 7 4 2 8 5 3 9 6
> d $ a [1] 7 8 9
18
R 4: Control Flow
http://stat.ethz.ch/R-manual/R-devel/library/base/html/Control.html http://www.statmethods.net/management/controlstructures.html
19
If structure 1/2
if (expression){
statements
}else if (expression){
statements }else{
statements }
● Use {} for your statement
● Use () for you expression
● Indentation is not
needed but good for reading
20
If structure 2/2
Generate a ramdon number from uniform distriction and test if it is larger than 0.5:
> a <- runif(1)
%generate random number from uniform(0,1)
> if (a>0.5){
+ print(paste('a =',a,'is larger than 0.5')) + }else if (a==0.5){
+ print(paste('a =',a,'equals than 0.5')) + }else{
+ print(paste('a =',a,'is less than 0.5')) + }
[1] "a = 0.783209139248356 is larger than 0.5"
21
for/while Loop
for (index = values){
statements }
while (expression is true){
statements }
Note:
Try to avoid loop if possible.
Matrix operation is much faster.
22
R 5: Functions
http://stat.ethz.ch/R-manual/R-devel/library/base/html/function.html http://www.statmethods.net/management/userfunctions.html
23
Define R function
Format:
function_name <- function(arg1, arg2, ... ){
statements
return(return_value) }
Example:
> average <- function(x) #define function + {
+ y = sum(x)/length(x) + return(y)
+ }
> z <- c(1:49)
> average(z) # call function average [1] 25
24
R packages
R has many useful packages to help with your job, check for a complete list of contributed
packages in
http://cran.r-project.org/web/packages/
Load the package by library(package)
On Windows you cam install Packages from the Packages menu. On command line, type
install.packages(Package_Name).