Functions
Learn to automate repeated tasks with functions.
Understanding functions
A function does nearly everything we do in R. Want to read in our data? We use the read.csv()
function. Want to calculate a mean? We use the mean()
function. Want to run a generalized linear mixed-effects model? Better use the glmer()
or glmmTMB()
function.
Functions are sets of commands that are bundled together to accomplish some task. Generally, but not always, functions require some input(s) and return some output(s). This can be as simple as the mean()
function, which requires a vector of numbers, or as complicated as the complex statistical models run throughout this course. Writing functions and loops requires an open mind and an ability to think in the abstract. That said, once we wrap our heads around it, it can open up many possibilities for us.
Why do we write functions?
Although R may seem like it has a function for every possible task, it actually doesn’t. Thus, there are many reasons why we may want to create our own functions. For example, we may want to write a function for any of the following tasks:
Get hands-on with 1200+ tech skills courses.