Writing custom functions in R

So far, we have been using existing packages in R to accomplish tasks.

But often, we will want our code to accomplish complicated tasks that others yet haven’t implemented as functions.

  • E.g. we may want to develop a new statistical tool or simulation
  • E.g. we may want to develop a “pipeline” that chains together multiple existing tools to create something new

Writing new functions is a great way to accomplish this.

Functions as “pipelines”

Toy example: Let’s say we are conducting an analysis where we first need to take a given number, add 2 to it, then multiple it by 3:

And if we needed to achieve this for several numbers?

Functions as “pipelines”

Toy example: Let’s say we are conducting an analysis where we first need to take a given number, add 2 to it, then multiple it by 3:

Instead, we can write it as a function:

Functions as “pipelines”

More realistic example: We want to calculate the Shannon Diversity for birds at the LSU Lakes for each month in 2023

An aside: What is Shannon Diversity?

Consider two communities: do these have equal “biodiversity”?

# A tibble: 5 × 3
  species commA commB
  <chr>   <dbl> <dbl>
1 a         150    38
2 b          20    42
3 c          10    36
4 d          10    44
5 e          10    40

(Columns show theoretical abundances)

  • Instead of just counting up species, Shannon Diversity is a metric that accounts for the fact that some communities may have more “even” representation of species than others

  • In the example above, Community A is more “predictable” – if we were to randomly pluck individuals from the community, we’d mostly get individuals of species “a”. In Community B, all species are basically equally likely.

  • Shannon diversity quantifies this distinction:

\[\overbrace{H'}^{\substack{\text{Shannon}\\{\text{index}}}} = -\sum_{i = 1}^{n} \overbrace{p_i}^{\substack{\text{proportional}\\ \text{abundance}}}*\overbrace{\text{ ln}(p_i)}^{\log\big(\substack{\text{proportional}\\ \text{abundance}}\big)}\]

Calculating Shannon diversity

Given the communities above, we can calculate Shannon diversity for each:

\[\overbrace{H'}^{\substack{\text{Shannon}\\{\text{index}}}} = -\sum_{i = 1}^{n} \overbrace{p_i}^{\substack{\text{proportional}\\ \text{abundance}}}*\overbrace{\text{ ln}(p_i)}^{\log\big(\substack{\text{proportional}\\ \text{abundance}}\big)}\]

Calculating Shannon diversity

We can combine these steps into a single function:

Calculating Shannon diversity for “real” datasets

A few weeks ago, we learned how to make this plot:

Let’s now work towards this

Step 0: Import the data and remake the original plot

Recall that we wrote the following code to make the “baseline” plot (without Shannon diversity)

library(tidyverse)
ebird_out <- readRDS(url("https://gitlab.com/gklab/teaching/rr-f26/-/raw/main/weekly-activities/week-05/ebird-UniversityLakes.rds"))

ebird_out |> 
  # Expand the dataset so that each row is one species in one checklist
  unnest(ebird_out) |># View()
  # Get rid of unused columns
  select(year, months, comName, sciName, howMany) |>  #View()
  filter(year == 2024) |> # View()
  summarise(total_seen = sum(howMany),
            n_obsevers = n(),
            .by = c(months, comName)) |> 
  mutate(avg_obs = total_seen/n_obsevers) |>
  ungroup() |> 
  group_by(months) |> 
  mutate(n_species = n()) |>  #View()
  mutate(facet_label = paste("Months: ",months, "No. of species: ", n_species)) |> # View()
  arrange(-avg_obs, .by_group = T) |> #View()
  mutate(rank_obs = row_number()) |> #View()
  filter(rank_obs < 21) |> #View()
  nest() |>  #print()
  mutate(monthly_plot =
           # Functional programming: 
           map(data, \(x)
               x |>
                 mutate(comName = fct_reorder(comName, avg_obs)) |>
                 ggplot(aes(x = avg_obs, y = comName)) +
                 geom_linerange(aes(xmin = 0, xmax = avg_obs)) +
                 geom_point() +
                 labs(title = x$facet_label)
               ))  |> #print()
  pull(monthly_plot) |>
  patchwork::wrap_plots()

Step 1: Calculate Shannon diversity for one month at a time

ebird_out <- readRDS(url("https://gitlab.com/gklab/teaching/rr-f26/-/raw/main/weekly-activities/week-05/ebird-UniversityLakes.rds"))

january_2024 <- 
  ebird_out |> 
  # Expand the dataset so that each row is one species in one checklist
  unnest(ebird_out) |># View()
  # Get rid of unused columns
  select(year, months, comName, sciName, howMany) |>  #View()
  filter(year == 2024 & months == "01") |> # View()
  summarise(total_seen = sum(howMany),
            n_obsevers = n(),
            .by = c(months, comName)) |> 
  mutate(avg_obs = total_seen/n_obsevers)

# Redefine the function for calculating shannon diversity
shannon_div <- function(abundances_vector) {
  prop_abun <- abundances_vector/sum(abundances_vector)
  ln_prop_abun <- log(prop_abun)
  -1*(sum(prop_abun*ln_prop_abun))
}


# Use this function to calculate Shannon diversity for Jan 2024

Step 2: repeat for several months

Change the following code to calculate Shannon diversity for Feb 2024:

january_2024 <- 
  ebird_out |> 
  # Expand the dataset so that each row is one species in one checklist
  unnest(ebird_out) |># View()
  # Get rid of unused columns
  select(year, months, comName, sciName, howMany) |>  #View()
  filter(year == 2024 & months == "01") |> # View()
  summarise(total_seen = sum(howMany),
            n_obsevers = n(),
            .by = c(months, comName)) |> 
  mutate(avg_obs = total_seen/n_obsevers)

Step 3: automate the process for each month…

Here is the original code we started out with. What do we need to change to calculate and show Shannon diversity for each month?

ebird_out |> 
  # Expand the dataset so that each row is one species in one checklist
  unnest(ebird_out) |># View()
  # Get rid of unused columns
  select(year, months, comName, sciName, howMany) |>  #View()
  filter(year == 2024) |> # View()
  summarise(total_seen = sum(howMany),
            n_obsevers = n(),
            .by = c(months, comName)) |> 
  mutate(avg_obs = total_seen/n_obsevers) |>
  ungroup() |> 
  group_by(months) |> 
  mutate(n_species = n()) |>  #View()
  mutate(facet_label = paste("Months: ",months, "No. of species: ", n_species)) |> # View()
  arrange(-avg_obs, .by_group = T) |> #View()
  mutate(rank_obs = row_number()) |> #View()
  filter(rank_obs < 21) |> #View()
  nest() |>  #print()
  mutate(monthly_plot =
           # Functional programming: 
           map(data, \(x)
               x |>
                 mutate(comName = fct_reorder(comName, avg_obs)) |>
                 ggplot(aes(x = avg_obs, y = comName)) +
                 geom_linerange(aes(xmin = 0, xmax = avg_obs)) +
                 geom_point() +
                 labs(title = x$facet_label)
               ))  |> #print()
  pull(monthly_plot) |>
  patchwork::wrap_plots()

Your turn

Work through the Software Carpentry lesson on writing functions in R:

https://swcarpentry.github.io/r-novice-gapminder/10-functions.html