Understandable and reusable code

Understandable chunks

Reuse

Function basics

function_name <- function(inputs) {
  output_value <- do_something(inputs)
  return(output_value)
}
{a = 2
b = 3
a + b}
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

Do Use and Modify. End of 1 hour class

Default arguments

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 Default Arguments.

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

Named vs unnamed arguments

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

Or

calc_shrub_vol(2.0, 0.8, 1.6)

Combining Functions

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

shrub_volume <- calc_shrub_vol(0.8, 1.6, 2.0)
shrub_mass <- est_shrub_mass(shrub_volume)
library(dplyr)
shrub_mass <- calc_shrub_vol(0.8, 1.6, 2.0) %>%
  est_shrub_mass()

Do Combining Functions.

shrub_mass <- est_shrub_mass(calc_shrub_vol(0.8, 1.6, 2.0))
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)

Documentation & Comments

Working with functions in RStudio