Session 7
2024-11-20
Source: How to create your own function in R (R for Ecology)
Refactoring is the process of making code:
…without changing behavior.
Source: Code Smells and Feels (2018)
To turn code into a function you need three things:
To turn code into a function you need three things:
Adapted from the tidyverse style guide:
return()
Strive to use verbs for function names:
Error in add_row(): argument ".data" is missing, with no default
Error in permute(): could not find function "permute"
Error in row_adder(): could not find function "row_adder"
Error in permutation(): could not find function "permutation"
Source: Functions from The tidyverse style guide.
return()
Only use return()
for early returns.
Use early returns to avoid else
and “nested” logic.
Source: Functions from The tidyverse style guide.
Use comments to explain the “why” not the “what” or “how”.
Source: Functions from The tidyverse style guide.
mutate()
and filter()
because they return an output of the same length as the input.summarize()
.If a function is type-stable it satisfies two conditions:
You can predict the output type based only on the input types (not their values).
If the function uses …, the order of arguments in does not affect the output type.
Source: Type-stability from The tidyverse style guide.
Four guiding principles for the “tidyverse”:
From Unifying principles in Tidy design principles (WIP)