Repetition

est_mass <- function(volume){
  mass <- 2.65 * volume^0.9
  return(mass)
}

est_mass(1.6)
est_mass(5.6)
est_mass(3.1)

Vectorize

est_mass <- function(volume){
  mass <- 2.65 * volume ^ 0.9
  return(mass)
}

est_mass(c(1.6, 5.6, 3.1))

Apply/Map functions

sapply

plant_vols <- c(1.6, 5.6, 3.1)
sapply(plant_vols, est_mass)

Other apply functions

lapply(plant_vols, est_mass)
est_mass_type <- function(volume, veg_type){
  if (veg_type == "tree"){
    mass <- 2.65 * volume^0.9
  } else {
    mass <- NA
  }
  return(mass)
}

est_mass_type(1.6, "tree")
plant_types <- c("tree", "grass", "tree")
est_mass_type(plant_vols, plant_types) # Warning & wrong result
mapply(est_mass_type, volume = plant_vols, veg_type = plant_types)

Do Use and Modify with Apply.

Integrating with dplyr

plant_data <- data.frame(volume = plant_vols, veg_type = plant_types)
mutate(plant_data, masses = est_mass(volume))
masses = mapply(est_mass_type,
                volume = plant_data$volume,
                veg_type = plant_data$veg_type)
plant_data$masess = masses
plant_data %>%
  rowwise() %>%
  mutate(masses = est_mass_type(volume, veg_type))

Do Crown Volume Calculation.

For loops

Basic for loop

for (item in list_of_items) {
  do_something(item)
}
volumes = c(1.6, 3, 8)
for (volume in volumes){
  print(2.65 * volume^0.9)
}
volume <- volumes[1]
print(2.65 * volume ^ 0.9)
volume <- volumes[2]
print(2.65 * volume ^ 0.9)
volume <- volumes[3]
print(2.65 * volume ^ 0.9)
for (volume in volumes){
   mass <- 2.65 * volume ^ 0.9
   mass_lb <- mass * 2.2
   print(mass_lb)
}

Do Task 1 in Use and Modify with Loops.

Looping with an index

for (i in seq_along(volumes)){
   mass <- 2.65 * volumes[i] ^ 0.9
   print(mass)
}
b0 <- c(2.65, 1.28, 3.29)
b1 <- c(0.9, 1.1, 1.2)
for (i in seq_along(volumes)){
   mass <- b0[i] * volumes[i] ^ b1[i]
   print(mass)
}

Storing results

b0 <- c(2.65, 1.28, 3.29)
b1 <- c(0.9, 1.1, 1.2)
masses <- vector(mode="numeric", length=length(volumes))
for (i in seq_along(volumes)){
   mass <- b0[i] * volumes[i] ^ b1[i]
   masses[i] <- mass
}

Do Tasks 2-3 in Use and Modify with Loops.

Looping over files

download.file("http://www.datacarpentry.org/semester-biology/data/collar-data-2016-01.zip", 
              "collar_data.zip")
unzip("collar_data.zip")
collar_data_files = list.files(pattern = "collar-data-.*.txt", 
                               full.names = TRUE)
results <- unlist(lapply(collar_data_files, get_numbers))

Do Multiple Files.