Statistical Methods with R

Writing R Code

Unit A · Chapter 02 · Lecture 02b

Developed by Jeffrey M. Girard

Roadmap: Basic Programming

  1. Assignment

  2. Naming

  3. Functions

  4. Vectors

Assignment

Assignment

  • It is often useful to store data in named objects
    • This makes the data easier to use and re-use
    • This makes the code easier to write and read
  • Which command is easier to follow?
    1. Dial 7 8 5 8 6 4 0 8 4 1
    2. Call Office Phone
  • Named objects are created using assignment
    • Give a name then an arrow then the data

office <- 7858640841

Assignment Live Coding

# LESSON: Assigning and printing

x <- 2
x

# ==============================================================================

# USECASE: Using an object in math (a la algebra) 

x * 4

2 * 4

# ==============================================================================

# LESSON: You must use assignment to update an object

x

x + 1

x # still 2

x <- x + 1
x # updated to 3

# ==============================================================================

# USECASE: We can use the same object multiple times in a line

(10 + x - 1) / x

# ==============================================================================

# USECASE: We can also use an object to create another object

y <- 10 + x
y

# ==============================================================================

# USECASE: We can also use multiple objects in a line

y / x

Naming

Naming

  • Object names can only include:
    • Letters: a-Z
    • Numbers: 0-9
    • Underscores: _
    • Periods: .
  • Additional Rules:
    • Must start with a letter or period
    • Cannot contain spaces or dashes
    • Cannot contain other symbols
    • Names are case-sensitive (ageAge)

Naming Live Coding

# LESSON: Good names are a balancing act

x <- 93 # what is it?

rate <- 93 # too short

heart_rate_in_beats_per_minute <- 93 # too long

heart_rate_bpm <- 93 # just right

# ==============================================================================

# PITFALL: Don't try to include spaces or dashes in names

heart rate <- 93 # error

heart-rate <- 93 # error

# ==============================================================================

# PITFALL: Don't try to include special symbols

age@time2 <- 12 # error

age_time2 <- 12 # correct

# ==============================================================================

# PITFALL: Don't try to put a number or underscore first

heart_rate_1 <- 93 # correct

1_heart_rate <- 93 # error

_heart_rate <- 93 # error

# ==============================================================================

# LESSON: Object names are case-sensitive

heart_rate <- 93

Heart_rate <- 88

heart_rate # still 93

Heart_rate # a new object

Functions

Functions

  • Recipes allow chefs to cook up tasty treats
    • Recipes call for ingredients
    • Recipes involve one or more steps
    • Steps transform ingredients into treats
  • Functions are like customizable recipes
    • Functions call for inputs (“arguments”)
    • Functions involve one or more lines of code
    • Code transforms inputs into outputs
    • Using functions requires parentheses (usually)

out <- f(in1, in2)

Functions Live Coding

# USECASE: Function can perform a task more easily and readably

# TEMPLATE: output <- function_name(input)

9 ^ (1 / 2)

x <- sqrt(9)
x

# ==============================================================================

# LESSON: We can also use functions to transform objects

y <- 9

sqrt(y)

# ==============================================================================

# LESSON: We can even use functions to transform the result of calculations

2 / 3

round(2 / 3)

# ==============================================================================

# LESSON: We can customize what a function does using arguments

# TEMPLATE: output <- function_name(argument, argument_name = argument_value)

round(2 / 3, digits = 2)

round(2 / 3, digits = 3)

# ==============================================================================

# LESSON: Some arguments are optional because they have default values

round(2 / 3) # the default value for digits is 0

round(2 / 3, digits = 0)

Vectors

Vectors

  • Vectors combine similar objects into a collection
    • I like to imagine a train pulling multiple cars
    • A vector is one object with many sub-objects
    • We refer to each sub-object as an element
  • Some functions transform each element in turn
    • Double the amount of cargo in every train car
  • Some functions summarize across elements
    • Calculate the total cargo across all train cars

v <- c(1, 2, 3)

Vectors Live Coding

# LESSON: We can combine multiple elements into a vector

# TEMPLATE: vector_name <- c(element1, element2, element3)

x <- 4 9 16 25 # error

x <- c(4, 9, 16, 25)
x

y <- c(2, 3)
y

# ==============================================================================

# LESSON: We can also combine multiple vectors and elements

c(x, y)

c(x, y, 20)

# ==============================================================================

# USECASE: Math operators will transform each element individually

x + 1

x * 3

x # but again, this won't be saved unless you use assignment

# ==============================================================================

# USECASE: Some functions will also transform each element individually

sqrt(x)

log(x)

# ==============================================================================

# USECASE: Other functions will summarize the vector with a single number

length(x)

sum(x)

mean(x)

average(x) # error

# ==============================================================================

# PITFALL: Missing values (NAs) are contagious

scores <- c(10, 12, 20, NA, 8)
mean(scores) # returns NA because the mean depends on the missing value
mean(scores, na.rm = TRUE) # returns mean of non-missing values