A practical introduction to R

Robin Lovelace

March 27, 2015

Installing and using the software

Installing and using R and RStudio

Productivity with RStudio

Key shortcuts in RStudio:

Command Action
Alt + Shift + K Show shortcuts
Ctrl + Enter Run current line of code
Ctrl + R Run all lines of code in the script
Tab Autocomplete*

Code used to generate that table

shortcuts <- data.frame(Command = c(
  "Alt + Shift + K", 
  "Ctrl + Enter",
  "Ctrl + R",
  "Tab"),
  Action = c("Show shortcuts",
    "Run current line of code",
    "Run all lines of code in the script",
    "Autocomplete*"))
kable(shortcuts)

R packages

There are 7,000+ 'add-on' packages to 'supercharge' R.

Easiest way to install them, from RStudio:

Tools -> Install Packages

or using keyboard shortcuts:

Alt + T ... then k

Install packages for this tutorial

Can be installed and loaded in 6 lines of code:

pkgs <- c("devtools", "shiny", "rgdal", "rgeos", "ggmap", "raster")
install.packages(pkgs) # install the official packages!
library(devtools) # enables installation of leaflet
gh_pkgs <- c("rstudio/leaflet", "robinlovelace/stplanr") 
install_github(gh_pkgs) # install packages on github
lapply(c(pkgs, "leaflet", "stplanr"), library, character.only = T)

Create and plot data

Basic data types

Anything that exists in R is an object. Let's create some with the <- symbol (= does the same job, before you ask!)

vector_logical <- c(TRUE, TRUE, FALSE)
vector_character <- c("yes", "yes", "Hello!")
vector_numeric <- c(1, 3, 9.9)

class(vector_logical) # what are the other object classes?
## [1] "logical"

Use the "Environment tab" (top right in RStudio) to see these

Automating things

To ask R what objects it has, we can use ls().

(Anything that happens is a function)

ls()
## [1] "pkgs"             "shortcuts"        "vector_character"
## [4] "vector_logical"   "vector_numeric"

Now we can automate the question: what class?

obs <- ls()[grep("ve", ls())]
sapply(X = mget(obs), FUN = class)
## vector_character   vector_logical   vector_numeric 
##      "character"        "logical"        "numeric"

Getting help in R

To find out what just happened, we can use R's internal help

The most commonly used help functions are:

help(apply) # get help on apply
?apply 
?sapply
??apply

The *apply family of functions are R's internal for loops. What about get()

?mget

The data frame

The fundamental data object in R.

Create them with data.frame()

data.frame(vector_logical, vector_character, n = vector_numeric)
##   vector_logical vector_character   n
## 1           TRUE              yes 1.0
## 2           TRUE              yes 3.0
## 3          FALSE           Hello! 9.9

Oops - we forgot to assign that. Tap UP or Ctl-UP in the console, then enter:

df <- data.frame(vector_logical, vector_character, n = vector_numeric)

Plotting data in R

plot() is polymorphic. Try plot(df) and ?plot:

## Help on topic 'plot' was found in the following packages:
## 
##   Package               Library
##   graphics              /usr/lib/R/library
##   raster                /usr/local/lib/R/site-library
## 
## 
## Using the first match ...

Subsetting data in R

The [] brackets, appending the object name, subset data.

A comma separates each dimension; nothing means everything:

df[1,] # all of the the 1st line of df
##   vector_logical vector_character n
## 1           TRUE              yes 1

In a 2d dataset, the following selects the 3rd line in the 3rd column:

df[3,3]
## [1] 9.9

Making objects spatial

There are 4 fundamental Spatial* data types in R, enabled by the foundational spatial package sp:

SpatialPixels()
SpatialPoints()
SpatialLines()
SpatialPolygons()

These are S4 R objects, with strictly defined slots. All such Spatial* objects have proj4string and bbox slots. Each can be extended as a Spatial*DataFrame to include data.

lnd <- shapefile("data/london_sport.shp")
class(lnd)
## [1] "SpatialPolygonsDataFrame"
## attr(,"package")
## [1] "sp"