INSTRUCTOR NOTE: Code examples should generally build up by modifying the existing code example rather than by retyping the full example.

Conditionals

10 > 5
"aang" == "aang"
3 != 3
"dog" %in% c("cat", "dog", "rabbit")
5 > 2 & 6 >=10
5 > 2 | 6 >=10
c(1, 1, 2, 3, 1) == 1
site = c('a', 'b', 'c', 'd')
state = c('FL', 'FL', 'GA', 'AL')
state == 'FL'
site[state == 'FL']
site[c(TRUE, TRUE, FALSE, FALSE)]

Do Tasks 1-4 in Choice Operators.

if statements

if (the conditional statement is TRUE ) {
  do something
}
x = 6
if (x > 5){
  x = x^2
}
x
x = 4
if (x > 5){
  x = x^2
}
x
veg_type <- "tree"
volume <- 16.08
if (veg_type == "tree") {
  mass <- 2.65 * volume^0.9
  }
mass

Do Task 1 in Basic If Statements.

veg_type <- "grass"
volume <- 16.08
if (veg_type == "tree") {
  mass <- 2.65 * volume^0.9
} else if (veg_type == "grass") {
  mass <- 0.65 * volume^1.2
}
mass
veg_type <- "shrub"
volume <- 16.08
if (veg_type == "tree") {
  mass <- 2.65 * volume^0.9
} else if (veg_type == "grass") {
  mass <- 0.65 * volume^1.2
} else {
  mass <- NA
}
mass

Do Tasks 2-3 in Basic If Statements.

Multiple ifs vs else if

x <- 5
if (x > 2){
  x * 2
}
if (x > 4){
  x * 4
}
x <- 5
if (x > 2){
  x * 2
} else if (x > 4){
  x * 4
}

Convert to function

est_mass <- function(volume, veg_type){
  if (veg_type == "tree") {
    mass <- 2.65 * volume^0.9
  } else if (veg_type == "grass") {
    mass <- 0.65 * volume^1.2
  } else {
    print("I don't know how to convert volume to mass for that vegetation type")
    mass <- NA
  }
  return(mass)
}

est_mass(1.6, "tree")
est_mass(1.6, "grass")
est_mass(1.6, "shrub")

Do Size Estimates by Name.

Automatically extracting functions

Nested conditionals

est_mass <- function(volume, veg_type, age){
  if (veg_type == "tree") {
    if (age < 5) {
      mass <- 1.6 * volume^0.8
    } else {
      mass <- 2.65 * volume^0.9
  }
  } else if (veg_type == "grass" | veg_type == "shrub") {
    mass <- 0.65 * volume^1.2
  } else {
    print("I don't know how to convert volume to mass for that vegetation type")
    mass <- NA
  }
  return(mass)
}

est_mass(1.6, "tree", age = 2)
est_mass(1.6, "shrub", age = 5)

Assign the rest of the exercises.