How to reuse your code… Use functions!
- Use a piece of code more than once? Create a function!
- Have a bit of code that is complex or fairly complicated? Create functions!
Why use functions:
- Makes your code more readable
- Let’s you reuse complex or repetitive code easily
- Uses the DRY principle: Don’t Repeat Yourself
What is a function:
- An encapsulated piece of code
- Takes an input or set of inputs, and outputs a single object
- R is a functinal programming language: Every action is a function in R
- ie.
mean()
, plot()
, [
, <-
, etc.
Creating a function
- Each function is composed of at least three to four parts:
- Assignment
<-
as an object (optional)
- The
function
call and if needed the arguments (aka options/settings)
- The code within the function
- Final object/data to output (the
return
)
- Make your code more readable, name your function descriptively:
scatter_plot
not e.g. someplot
extract_pvalue
not e.g. p
or value
- Be descriptive with the code in the function too
A function looks like:
A very simple example:
Document your functions
Use Ctrl-Shift-Alt-R
with cursor in function when using RStudio (only used in
.R
files, not .Rmd
files)
Should look like:
if else in functions
- Control how your function works using
if else
:
Using functions from other packages in your function
Sometimes you’ll come across this ::
. For instance:
- This tells R to take the function
select
from the package dplyr
.
- Better to use this style within a function rather than use
library()
- Using
library()
within a function is bad practice
- Let’s you know which commands come from which package
- Better documents your function
- Makes it more readable and transparent
Code used in session: