AE 10: Writing functions
Packages
We will use the following packages in this application exercise.
- {tidyverse}: For data import, wrangling, and visualization.
- {palmerpenguins}: For the
penguins
dataset
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.
Conditions in R are raised by three distinct functions:
# 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
- Exercises are derived from From R User to R Programmer and licensed under CC BY 4.0.