AE 10: Writing functions

Application exercise
Modified

March 3, 2025

Packages

We will use the following packages in this application exercise.

  • {tidyverse}: For data import, wrangling, and visualization.
  • {palmerpenguins}: For the penguins dataset
library(tidyverse)
library(palmerpenguins)

# create synthetic dataset for vector function exercises
set.seed(123)

vals <- tibble(
  # generate 10,000 observations drawn from an exponential distribution
  # with rate of 10
  x = rexp(10000, 10)
)

Write a vector function

Your turn: Write a function that performs the Box-Cox power transformation using the value of (non-zero) lambda (\(\lambda\)) supplied.

\[bc = \frac{x^{\lambda} - 1}{\lambda} \text{ for }\lambda \ne 0\]

Set the default \(\lambda = 1\).

# add code here

Your turn: Revise your function to check if \(\lambda \ne 0\). If \(\lambda = 0\), generate an error with an informative message.

Generating conditions in R

Conditions in R are raised by three distinct functions:

  • stop() - Stops execution of the current expression and executes an error action.
  • warning() - Generates a warning message that corresponds to its argument(s) and (optionally) the expression or function from which it was called.
  • message() - Generate a diagnostic message from its arguments.
# add code here

Demonstration: Revise your function for:

\[ bc = \begin{cases} \frac{x^{\lambda} - 1}{\lambda} & \text{for }\lambda \ne 0\\ \ln(x) & \text{for }\lambda = 0 \end{cases} \]

# add code here

Write a data frame function

Your turn: Write a function to calculate the median, maximum and minimum values of a variable grouped by another variable. Test it using the penguins data set.

# add code here

Acknowledgments