Intermediate R II: Functions cont’d, iteration, and getting help

Session 8

September 28, 2023

Before we jump in…

Show and tell (Late October)

  • An opportunity to apply workshop skills to your own work.
  • You could apply different parts to different projects, or more integratively to one single project.
  • Optional, but encouraged!

Some inspirations

  • Turn the project folder for one of your current research project into a git/GitHub repo and/or R project
  • Modify an R script to use functions, conditionals, or best-practices for code formatting
  • Improve directory organization for project or your entire computer!

Today’s objectives

  • Modify our data cleaning function to apply to different islands
  • Use iteration to apply this function to each island
  • Organize our workflow into “functions” and “running” scripts
  • Learn how to get help with more advanced topics

Part I: Generalizing a function

  • Open up your Rproject from Tuesday
  • Coding objectives:
    • Make sure the function we wrote works
    • Apply this function to different islands by swapping URLS
    • Add “ifelse” logic to avoid having to re-type the URL every time

Part II: Iteration

Iteration by hand

my_first_site <- read.csv("data_first.csv")
my_second_site <- read.csv("data_second.csv")
my_third_site <- read.csv("data_third.csv")

Why use code to iterate?

  • Less code: fewer bugs, easier to understand
  • Easier to apply to new situations
  • Faster to write, maybe faster to run

Iteration using for loops

  • Coding objectives:
    • Write a for loop to apply our cleaning function to each island
    • Store the results in a list
    • Convert this list back to a dataframe

Iteration using purrr::map

  • Coding objectives:
    • Use purrr::map as an alternative to a for loop
    • Demonstrate purrr applied to more complex workflows

Part III: Getting help

Wrap-up

Commit this week’s work and create a new PR.

Homework

  • Identify a section of your code that could be made more efficient using a for loop or iterating using a function
  • Start thinking about show-and-tell opportunities!