This code has been kindly contributed by Robin Edwards (from UCL CASA).

There are many useful introductory guides out there to R, but below is the kind of thing I now wish I’d been given when I first started using it – something with simple logically-progressive examples and minimal explanatory text. Copy the text below into a new script in R and run line-by-line to give a quick intro to many of R’s most basic principles and functionality. You can also download a text file with it here. It is by no means comprehensive, even at the most basic level, but still I hope someone finds it useful. You may want to look at RStudio as it is more user-friendly.

## A CRASH COURSE IN [R] PROGRAMMING

## Robin Edwards (geotheory.co.uk), March 2013

## In RStudio run through line-by-line using Ctrl + Enter

# basic R environmental functions

x=3.14159; y=’hello world’; z=TRUE # create some objects. In RStudio they’ll appear in ‘Workspace’

ls() # list the objects in the Workspace

print(y) # print information to R ‘Console’

rm(y) # remove an object

rm(list=ls()) # remove all

getwd() # find current working directory

setwd(“/Users/robinedwards/Documents”) # set working directory as preferred

print ( “R ignores the ‘white-space’ in command syntax” )

# use ‘?’ for help on any R function (if its library is loaded in the session)

?max

??csv # search for a text string in R documentation library

library(help=utils) # get help on a particular package (list its functions)

# ‘str’ is a powerful tool for investigating the underlying structure of any R object

str(max)

# CREATING AND MANIPULATING R OBJECTS

# assigning values to variables

n = 5 # is possible but

n 5 -> n

rm(n)

# R objects can be of various data types, but probably most common are ‘numeric’ and ‘character’

( num ( char <- ‘any text string’ )

# create a VECTOR (array) using the ‘c()’ concatenate function

( vec

# a vector series

( vec

# R vectors can be accessed in various ways using [ ] brackets

vec[3]

vec[3:6]

vec[ c(1,3,8) ]

vec[vec > 15]

# check a vector contains a value

5 %in% vec

12 %in% vec

# finding first index position of a matching value/sting

( x = c(‘one’, ‘five’, ‘two’, 3, ‘two’) )

match(‘two’, x)

match(c(‘two’,’five’), x)

# a MATRIX is a 2D vector (essentially a vector of vectors) of matching data type

( matrx = matrix(1:15, 3, 5) )

( matrx dim(matrx) print(matrx)

t(matrx) # a matrix can be easily transposed

# an ARRAY is a generic vector but with more flexibiity. A 1D array is the same as a normal vector,

# and a 2D array is like a matrix. But arrays can store data with ‘n’ dimensions:

( arry

# Using square brackets on arrays

arry[12] # a single criterion (argument) selects the array’s n’th record

arry[3,1,2] # or use multiple arguments that reflect the array’s dimensionality

arry[,,2]

arry[,1,]

# a DATA.FRAME is like a matrix, but accomodates fields (columns) with different data types

(df

# They can be viewed easily

View(df)

# examine their internal stucture

str(df)

# data interrogation with square brackets

df[1,]

df[2:3,]

df[,1]

df[2,1]

# data.frame and matrix objects can have field (column) and record (row) names

dimnames(df)

colnames(df)

names(df) # not for matrix objects

row.names(df)

# interrogate data.frames by field name using the ‘$’ operator. the result is a simple vector

df$name

df$name[2]

# names can be reassigned

names(df) row.names(df) print(df)

# check dimensions of vector/matrix/array/data.frame objects

length(vec)

dim(df)

dim(arry)

nrow(df)

ncol(df)

# R has various inbuilt data.frame datasets used to illustrate how functions operate e.g.

data()

InsectSprays # this guide makes use of these datasets

warpbreaks

# examine contents

head(InsectSprays) # list the top records of a vector / matrix / d.f.

tail(InsectSprays, n=3) # bottom the 3

summary(InsectSprays) # summarise a data vector

# aggregate() is a powerful function for summarising categorical data

aggregate(InsectSprays$count, by=list(InsectSprays$spray), FUN=mean)

sumInsects names(sumInsects) print(sumInsects)

# subset/apply filter to a data.frame

warpbreaks[warpbreaks$wool==’A’,] # by 1 condition

warpbreaks[warpbreaks$tension %in% c(‘L’,’M’),] # multiple conditions

# adding entries is possible (if a bit tricky)

(newrow (warpbreaks

# but LISTS are better at this

lst = list()

# ways to assign/add items

lst[1] = “one”

lst[[2]] <- “two”

lst[length(lst)+1] <- “three”

print(lst)

# data retrieval

lst[[1]] # double brackets means the object returned is of the data