Lesson 1: R for Newbies

Learning Objectives

  • Discover what R is
  • Understand the advantages of R
  • Find your way around RStudio
  • Get to know the basic R building blocks of R

What is R?

  • R is a free software environment for statistical computing and graphics
  • It works with a wide variety of platforms

Why R?

  1. You can do anything in R.
  2. R facilitates reproducible science
  3. Long term gain from upfront investment

RStudio - Making R a Breeze

  • RStudio helps you write in R by:
    • sending your written code to R
    • ‘syntax-highlighting’
    • keeping a history of your actions
    • giving you tools to fix your code when it doesn’t work (debugging)

RStudio - Live Coding Session

R building blocks

  • The 3 main building block of R are:
    • names
    • data: vectors and data frames
    • functions

Names

  • We use the <- assignment operator to assign a name.
answer <- 42
msg <- "Hello World!"
answer
## [1] 42
msg
## [1] "Hello World!"

  • You can perform math!
x <- 2
y <- 4

x + y
## [1] 6
x * y
## [1] 8
x / y
## [1] 0.5

Data

  • Vectors
  • Dataframes

  • Vectors: a series of things of the same type, e.g.:
  • numbers: 1, 4, 9, 16, 25
  • characters: “Q”, “W”, “E”, “R”, “T”, “Y”
  • logicals: TRUE, FALSE, TRUE, TRUE, FALSE

  • Make your own vectors with c():
name <- c("Danny", "Esther", "Karen", "Kariem")
age <- c(35, 33, 32, 41)
sex <- c("M", "F", "F", "M")
height <- c(183, 160, 155, 178)
weight <- c(85, 60, 53, 70)

name
## [1] "Danny"  "Esther" "Karen"  "Kariem"
age
## [1] 35 33 32 41
sex
## [1] "M" "F" "F" "M"
height
## [1] 183 160 155 178
weight
## [1] 85 60 53 70

  • Mixing types
mixed <- c(113, "Tom", TRUE)
mixed
## [1] "113"  "Tom"  "TRUE"
name
## [1] "Danny"  "Esther" "Karen"  "Kariem"
age
## [1] 35 33 32 41

  • A bit more on datatypes

  • Dataframes: many vectors combined in a grid, analagous to a spreadsheet.
class_demographics <- data.frame(name, age, sex, height, weight)

class_demographics
##     name age sex height weight
## 1  Danny  35   M    183     85
## 2 Esther  33   F    160     60
## 3  Karen  32   F    155     53
## 4 Kariem  41   M    178     70

Functions

  • Functions are litte machines that perform specific tasks.
  • R has loads of built-in functions
  • You can write your own!

Anatomy of a function

ed.moveforward()

ed.moveforward()

ed.moveforward(speed = "fast")

ed.moveforward(speed = fast)

ed.moveforward(speed = "fast")
ed.turnright()
ed.turnright()
ed.moveforward(speed = "fast")

ed.moveforward scripted

  • Use R functions on your class_demographics
summary(class_demographics)

Help Files

  • Help files tell you how functions work.
  • Clear, but technical language