Understandable and reusable code

Understandable chunks

Reuse

Function basics

function_name <- function(inputs) {
  output_value <- do_something(inputs)
  return(output_value)
}
calc_shrub_vol <- function(length, width, height) {
  volume <- length * width * height
  return(volume)
}
calc_shrub_vol(0.8, 1.6, 2.0)
shrub_vol <- calc_shrub_vol(0.8, 1.6, 2.0)

Do Writing Functions.

length <- 1
width <- 2
height <- 3

calc_shrub_vol <- function() {
  volume <- length * width * height
  return(volume)
}
calc_shrub_vol <- function(length = 1, width = 1, height = 1) {
  volume <- length * width * height
  return(volume)
}

calc_shrub_vol()
calc_shrub_vol(width = 2)
calc_shrub_vol(0.8, 1.6, 2.0)
calc_shrub_vol(height = 2.0, length = 0.8, width = 1.6)

Do Use and Modify.

  • Discuss why passing a and b in is more useful than having them fixed*

Combining Functions

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

shrub_mass <- est_shrub_mass(calc_shrub_vol(0.8, 1.6, 2.0))

library(dplyr)
shrub_mass <- calc_shrub_vol(0.8, 1.6, 2.0) %>%
  est_shrub_mass()
est_shrub_mass_dim <- function(length, width, height){
  volume = calc_shrub_vol(length, width, height)
  mass <- est_shrub_mass(volume)
  return(mass)
}

est_shrub_mass_dim(0.8, 1.6, 2.0)

Do Nested Functions.