Intermediate R: Functions and control flow

Session 8

September 26, 2024

Learning objectives

  • Write custom functions
  • Use if-else logic to generalize functions

Picking up from last week

  • Commit last week’s work to GitHub and push
  • Merge your work to main!
  • Create a new branch for today’s work and pull

Revisiting the penguins data

  • Note that units are in mm and g
  • Today we’ll convert these to imperial measurements (inches and pounds)
  • For this, we’ll use functions.

Functions

What are functions in R?

  • We use pre-written functions constantly.
  • Automated “recipes” for executing code
  • Inputs (“arguments”) and outputs

Why write our own functions?

  • Avoid repetition (+ mistakes)
  • Enhance portability + reproducibility

Writing a function objectives

  • Convert our data wrangling script into a function
  • Break this function into smaller, human-readable functions
  • Make this function flexible to apply to other data

Anatomy of a function

# Defining a function
# a_function will be the name of the function
# arguments go within the ()
# code goes in the curly braces

a_function <- function(an_argument) {
  # code using an_argument to produce final_output
  
  # whatever is inside return() comes out of the function
  return(final_output) 
}

# Run the code to create the function
# Then you can use it:
# a_function(<some_input>)
# 

Coding time

Write a function to convert metric to imperial measurements.

Sourcing functions

  • You can store functions in separate R scripts and import them to your main working script.
  • This helps keep your main script simple and keeps your whole repo organized.
  • Use source(<path_to_functions_script>) in your main script.

Coding time

Save our function in a separate R script and source it from a data wrangling script.

Control flow with conditionals

What are conditionals?

  • Decide which action to take based on whether some condition is TRUE or FALSE
  • Balance readability and flexibility in scripts and functions

Conditional syntax

if(<condition>) {
  <action to take if TRUE>
}

Conditional syntax

if(<condition>) {
  <action to take if TRUE>
} else {
  <action to take if FALSE>
}

Defining conditions

  • == for “is equal to”
  • != for “not equal to:
  • <, > for less than/greater than
  • <=, >= for less than or equal to/greater than or equal to
  • is.na() for is it NA?
  • %in% for, is this value in a vector of possibilities
  • …and more!

Coding time

  • Use conditionals to make a flexible function.

Finishing up

  • Commit your changes and push
  • Open a pull request.

Resources

Your tasks

  • Identify parts of your colloquium project code that could be turned into functions.
  • Good candidates are: repeated sections, complicated sidebars to the main flow
  • Convert these sections to functions and source() them to clean up the main script.