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)
}

volumes = c(1.6, 5.6, 3.1)
est_mass(volumes)
library(stringr)

str_to_upper("tree")
plant_types <- c("tree", "grass", "tree")
str_to_upper(plant_types)
plant_data <- data.frame(volumes, plant_types)
str_to_upper(plant_data["plant_types"])
str_to_upper(plant_data$plant_types)
plant_data$veg_type_upper = toupper(plant_data$plant_types)

Do Vectorized Genus Extraction.

Apply/Map functions

sapply & lapply

sapply(X = volumes, FUN = est_mass)
c(est_mass(volumes[1]), est_mass(volumes[2]), est_mass(volumes[3]))
lapply(X = volumes, FUN = est_mass)

Do Vectorized Genus Extraction.

Other apply functions

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")
est_mass_type(volumes, plant_types) # Warning & wrong result
mapply(FUN = est_mass_type, volume = volumes, veg_type = plant_types)

Do Size Estimates Vectorized 1-2.

apply (optional)

counts = data.frame(sp1 = c(5, 4, 7, 6), sp2 = c(6, 2, 6, 9), sp3 = c(8, 16, 1, 0))
counts
apply(X = counts, MARGIN = 1, FUN = sum)
apply(X = counts, MARGIN = 2, FUN = sum)

Integrating with dplyr

One result per row

plant_data
mutate(plant_data, masses = est_mass(volumes))
plant_data %>%
  rowwise() %>%
  mutate(masses = est_mass_type(volumes, plant_types))

Do Size Estimates By Name.

One result per group

get_biomass <- function(volumes){
  masses <- est_mass(volumes)
  biomass <- sum(masses)
  return(biomass)
}

plant_data %>%
  group_by(plant_types) %>%
  summarize(biomass = get_biomass(volumes))