Video Notes
In R, we learn about all sorts of built-in functions such as mean, sd, sum, etc.
Oftentimes, it can be useful to define your own custom functions when there’s some calculation or action you need to execute repeatedly in your code.
To familiarize ourself with the syntax of a function, here’s a simple example:
is_even <- function(num) {
return(num %% 2 == 0)
}
- The first line assigns a new function to an object named
is_even
- In parenthesis, we define any parameters this function can accept - in this case, we defined a single parameter,
num
- The curly braces {} contain the code that will run when the function is called; in this case there is just a single line of code, but there could be many.
- The return statement is used to return a value from our function
Here are some examples invoking this function:
is_even(1) # FALSE
is_even(12) # TRUE
is_even(999) # FALSE
Functions with no returns
Not every function will return a value. For example, the following function can be used to save a data file and output a confirmation message to the console. No particular value is returned:
save_to_cwd <- function(data, filename) {
filepath <- file.path(getwd(), filename)
write.csv(data, filepath, row.names = FALSE)
message("File saved to: ", filepath)
}
Organize commonly used functions
It can be helpful to organize commonly used functions into their own scripts file that can then be included in other scripts and used as needed.
For example
For example, if we moved our is_even function to a separate script called utils.R, we could then include it in our original script using the source method:
source('utils.R')
is_even(13) # FALSE
Unlock all notes for $4
For $4, you’ll get 6 months of unlimited access to the notes for the above video
and all of my other 200+ guides and videos.
This is a one-time payment— no subscriptions or auto-renewals to worry about cancelling.
Your support helps me continue creating free, high-quality videos. Thank you!