Slides: rpubs.com/RobinLovelace

R as a giant calculator

5 * 5
1 + 4 * 5
4 * 5 ^ 2
sin(90)
sin(0.5 * pi)

Objects

a <- 1
b <- 2
c <- "c"
x_thingy <- 4
a + b
a * b
a + c
a / x_thingy

Adding and removing objects

ls()
## [1] "a"        "b"        "c"        "x_thingy"
x <- x_thingy
rm(x_thingy)
x
## [1] 4
ls()
## [1] "a" "b" "c" "x"

Harmonograph example

Practical 1: Getting used to RStudio and R

  • Open RStudio and have a look around
  • Create a new project
  • Create a new R Script: pass code to the console with Ctl-Enter
  • Use R as a calculator: what is:

\[ \pi * 9.15^2 \]

  • Explore each of the 'panes'
  • Find and write down some useful shortcuts (Alt-Shift-K on Windows/Linux)

Basic R functions and behaviour

Functions and objects

In R:

  • Everything that exists is an object
  • Everything that happens is a function
# Assignment of x
x <- 5
x
## [1] 5
# A trick to print x
(x <- 5)
(y <- x)

Functions

sin(x)
## [1] -0.9589243
exp(x)
## [1] 148.4132
factorial(x)
## [1] 120
sinx <- sin(x)

R is vector based

x <- c(1, 2, 5)
x
## [1] 1 2 5
x^2
## [1]  1  4 25
x + 2
## [1] 3 4 7
x + rev(x)

The classic programming way: verbose

x <- c(1, 2, 5)
for(i in x){
  print(i^2)
}
## [1] 1
## [1] 4
## [1] 25

Creating a new vector based on x

for(i in 1:length(x)){
  if(i == 1) x2 <- x[i]^2
  else x2 <- c(x2, x[i]^2)
}
x2
## [1]  1  4 25

Data types

R has a hierarchy of data classes, tending to the lowest:

  • Binary
  • Integer (numeric)
  • Double (numeric)
  • Character

Examples of data types

a <- TRUE
b <- 1:5
c <- pi
d <- "Hello Leeds"
class(a)
class(b)
class(c)
class(d)

Data type switching

ab <- c(a, b)
ab
## [1] 1 1 2 3 4 5
class(ab)
## [1] "integer"

Test on data types

class(c(a, b))
## [1] "integer"
class(c(a, c))
## [1] "numeric"
class(c(b, d))
## [1] "character"

Sequences

x <- 1:5
y <- 2:6
plot(x, y)

Sequences with seq

x <- seq(1,2, by = 0.2)
length(x)
## [1] 6
x <- seq(1, 2, length.out = 5)
length(x)
## [1] 5

Practical: 45 minutes

Working through Chapter 20 of R for Data Science: http://r4ds.had.co.nz/vectors.html

  • Work through 20.3

  • Challenge: create an atomic vector of 3 characters and an NA

  • Challenge: create an atomic vector of 5 numeric vectors

  • Challenge: create a list containing logical, character and numeric vectors
    • What happens to the class if you unlist this list?
  • Complete all the code examples in 20.4
    • Challenge: what are the outcomes of the following commands?:
x = 1:10
x[c(1, NA)]
x[2 * 3]
x[-2 * 3]

Data loading practical

  • Run the code in download-data.R
  • Check that the files have downloaded and unzipped OK
    • If so: you've used R as a file manager!
  • Work through pages 4, 5 and 6 in the Creating-maps-in-R tutorial