Introduction to R
Introduction to R
i gh-
Scripting H l
e
(R, MATLAB, IDL) Lev es
uag
ng
La
Object Oriented
(C++, Java)
Functional
languages l
(C, Fortran) v e
w-Le ges
Lo gua
Assembly Lan
3
Features of R
6
Variables and assignment
To create a matrix:
# matrix() command to create matrix A with rows and cols
A=matrix(c(54,49,49,41,26,43,49,50,58,71),nrow=5,ncol
=2))
B=matrix(1,nrow=4,ncol=4)
To access matrix elements: Statistical operations:
# matrix_name[row_no, col_no] rowSums(A)
A[2,1] # 2nd row, 1st colSums(A)
column element rowMeans(A)
A[3,] # 3rd row colMeans(A)
A[,2] # 2nd column of the # max of each columns
matrix apply(A,2,max)
A[2:4,c(3,1)] # submatrix of # min of each row
2nd-4th elements of the 3rd and 1st apply(A,1,min)
columns
Element
A["KC",]by element
# access ops:
row by name, Matrix/vector multiplication:
"KC"
2*A+3; A+B; A*B; A/B; A %*% B; 10
Useful functions for vectors and
matrices
• Find # of elements or dimensions
• length(v), length(A), dim(A)
• Transpose
• t(v), t(A)
• Matrix inverse
• solve(A)
• Sort vector values
• sort(v)
• Statistics
• min(), max(), mean(), median(), sum(), sd(), quantile()
• Treat matrices as a single vector (same with sort())
Graphical display and plotting
• Large data sets are better loaded through the file input
interface in R
• Reading a table of data can be done using the read.table()
command:
• a <- read.table(“a.txt”)
• The values are read into R as an object of type data frame (a
sort of matrix in which different columns can have different
types). Various options can specify reading or discarding of
headers and other metadata.
• A more primitive but universal file-reading function exists,
called scan()
• b = scan(“input.dat”);
• scan() returns a vector of the data read
Programming in R
• The following slides assume a basic
understanding of programming concepts
Additional resources
• Beginning R: An Introduction to Statistical Programming
by Larry Pace
• Introduction to R webpage on APSnet:
http://www.apsnet.org/edcenter/advanced/topics/
ecologyandepidemiologyinr/introductiontor/Pages/default.aspx
• The R Inferno:
http://www.burns-stat.com/pages/Tutor/R_inferno.pdf
17
Conditional statements
23