PROG103: Branches and Loops

This is the third module of the Programming track. By the end of this module, you’ll learn how to:

Pre-class preparation

Set up the PROG103module on your computer (see Module Setup and Submission). There you’ll find the guided notes and exercises to accompany these recorded lectures.

Lectures

Conditions in R

Making choices with if, else, and else if

Repeating yourself with vectorized functions

Repeating yourself with for loops

In-class activity

In PROG102 you wrote functions to extract temperatures, exposures, and time from the kefj dataset. Here, you’ll use loops and if-then statements to calculate extreme hot and cold exposure across sites and season.

Traiger et al. (2022) defined extreme hot and cold exposure as air temperatures ≥25°C and ≤-4°C, respectively. The goal here is to calculate the hours of extreme hot and cold exposure on average per day in each site and season. For example, on average, how many hours of extreme heat did mussels in Aialik experience in summer?

Review: write a function

Your first task is to review what you learned in PROG102 by writing a function to encapsulate a procedure.

P1 Describe succinctly what the following code does. This should be a high-level, one-sentence description, not a line-by-line breakdown.

Tip

Remember the most common sampling interval from PROG101! Each temperature record represents 30 minutes of time.

site <- "Nuka_Pass"
season <- "Late winter"
n_cold <- sum(kefj_site == site &
                kefj_season == season &
                kefj_temperature <= -4 &
                kefj_exposure == "air")
n_total <- sum(kefj_site == site &
                 kefj_season == season)
hours_cold <- n_cold * 30 / 60
days_total <- n_total * 30 / 60 / 24
hours_cold_per_day <- hours_cold / days_total
hours_cold_per_day

P2 Let’s turn that code chunk into a function. What would you call that function? How many parameters should it take and what would you call them?

P3 Write a function to encapsulate the code chunk above. Check that it contains all five parts of a function.

Make an extreme choice

The code chunk above focuses on extreme cold exposure, but we would like to use a similar procedure for extreme heat exposure. In order, here’s what we’ll do.

  1. Use an if else statement to create a logical vector indicating whether temperatures are extreme.
  2. Incorporate the new logical vector into our old code chunk to make it more flexible.
  3. Add a parameter to your function so it can handle extreme heat or cold.

P4 Fill in the code below to create a logical vector indicating extreme temperatures.

extreme_type <- "cold"
if (??? == "???") {
  is_extreme <- kefj_temperature ??? ???
} ??? {
  ???
}

P5 Copy-paste the code from P1 and edit it to incorporate the is_extreme vector into the extreme temperature exposure procedure.

P6 Copy-paste the function you wrote in P3 and edit it to add a parameter that lets you switch between extreme heat and cold exposure.

Important

Make sure that when you edit the function you choose readable names for the function, its parameters, and any variables you define in the body!

Season to taste

In the previous section, you used if then to make choices. Now, you’re going to use for loops to repeat an operation over multiple inputs. In order, you’ll:

  1. Identify the unique seasons to loop over
  2. Calculate extreme heat and cold exposure in each season (for a given site)
  3. Add a nested loop to iterate over the unique sites, as well

When you’re done, you’ll use the results of your loops to find the mildest season in Alaska.

P7 What seasons are in the kefj dataset? What function would you use to identify them?

P8 Fill in the blanks below to make a for loop that prints the extreme hot and cold exposure across seasons at site Aialik.

seasons <- ???
for (??? in ???) {
  heat_exposure <- ???(???, ???, "hot")
  cold_exposure <- ???
  print(paste("Aialik", ???, heat_exposure, cold_exposure))
}

P9 Copy-paste your answer to P8 and add a nested for loop to iterate across sites as well as seasons.

P10 Examine your results from P9. You should find two outputs where both extreme heat and cold exposure were 0. What season were they in?

Recap and next steps

In this module you learned how to make make decisions and repeat yourself - key skills for writing complex code!

This completes the essential coding skills you need for this class. Options for next steps are:

INFO101 - learn how data are organized in tables.

PRST101 - learn to summarize data and prepare for probability and statistics.

COMM101 - learn to visualize data and begin making publication-quality figures (but do INFO101 first).

Fill out the PROG103 reflection to complete this module. Well done!

References

Traiger, Sarah B., James L. Bodkin, Heather A. Coletti, Brenda Ballachey, Thomas Dean, Daniel Esler, Katrin Iken, et al. 2022. “Evidence of Increased Mussel Abundance Related to the Pacific Marine Heatwave and Sea Star Wasting.” Marine Ecology 43 (4). https://doi.org/10.1111/maec.12715.