# Introduction to R

This is a very simple Introduction to R to allow users to become used to working with data in R.  R is available for Windows, Linux and MacOS from http://www.r-project.org

We also recommend use of a text editor that knows about R code - such as Tinn-R: http://www.sciviews.org/Tinn-R/.  The code below is executable and can be pasted directly into R.  Lines and text that begin with # are comments that will be ignored by R.  Lines that are red are code and will be interpreted.

 # variables - storing information# simple calculations1010 * 2010^4 # simple calculations of a variablex <- 10xx * 20x^4 # vectorsc(1,2,3,4) # what does c() mean?# c is a function - combine?c # lets assign the vector 1,2,3,4 to variable vv <- c(1,2,3,4)v # simple calculations on a vectorv * 20v^4x <- v ^ 4vx # acessing parts of vectorsxxx[c(1,4)] # useful functions to apply to vectorssum(v)mean(v)length(v) # generating sequences of numbers1:10c(1:10)  # exactly the same thing seq(1,10, by=1)seq(1,10, by=.5) x <- 1:10rep(x, times=3)rep(x, times=3, each=5) # logical vectorsx <- rep(1:10,times=3)x > 5gt5 <- x > 5gt5x[gt5] # matricesx <- array(1:20, dim=c(4,5))   xx*20x^2 x[1,2] # get element in first row, second columnx[1,]  # get first rowx[,3]  # get third column t(x)  # transpose the matrix y <- array(20:40, dim=c(4,5)) cbind(x,y) # combine by columnsrbind(x,y) # combine by rows # lists - like a named vector# a list is kind of like a vector, with the elements named as well as numbered:lst <- list(name="Fred", wife="Mary", no.children=3,                   child.ages=c(4,7,9))                   lst lst[]   # get the first element in the listlst\$name   # get the value in the list referred to by 'name' # data frames - useful matrices :)mirrors <- read.csv(paste(R.home("doc"), "CRAN_mirrors.csv", sep="/"), row.names=1)# mirrors <- getCRANmirrors(all = FALSE, local.only = FALSE)     # alternative is.data.frame(mirrors) # check and see if mirrors is a data frame mirrors[1:5, 1:3]  # mirrors can be accessed in the same way as a matrix colnames(mirrors)  # column namesrownames(mirrors)  # row names mirrors\$Host  # columns can be accessed like a listmirrors\$URL # we can also access them using the [..,..] notation and names, instead of numbersmirrors[1:5,1:3]mirrors[1:5,c("Country","City","URL")]mirrors["Austria", 1:3] # save datasave.image()