Understandable and reusable code

Understandable chunks

Reuse

Function basics

function_name <- function(inputs) {
  output_value <- do_something(inputs)
  return(output_value)
}
add <- function(a, b) {
  total <- a + b
  return(total)
}
add(2, 3)
summed <- add(2, 3)
add <- function(a=1, b=2) {
  total <- a + b
  return(total)
}

add()
add(b=3)
add(4, 5)
a <- 1
b <- 2

add <- function() {
  total <- a + b
  return(total)
}

Do Exercise 1 - Use and Modify, Task 3 and Exercise 2 - Writing Functions.

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

Nesting Functions

make_pie_filling <- function(stuff) {
  filling <- pi * stuff
  return(filling)
}
make_pie <- function(stuff, crust) {
  pie <- crust + make_pie_filling(stuff)
  return(pie)
}

Do Exercise 3 - Nested Functions.