Creating Functions

Learn to define functions in R and the best practices for using them.

Functions are an essential element of code organization. Without functions, our code quickly becomes a tangled mess of repeated lines and nested loops. But with them, we can reduce complexity, increase readability, and save valuable time by reusing code.

Like in other programming languages, we can define functions in R that take a set of inputs, process them, and return some outputs. Creating functions allows us to streamline our code by reducing repetitive sections and keeping our code modular, so we can easily recall steps that we’ve already coded. And the best part? We can create functions (and even packages!) to share with colleagues.

Let’s take a look at a code example of how to create functions in R:

Get hands-on with 1200+ tech skills courses.