How to Make Functions in R

R is a functional programming language. Most of the time, you use other people’s functions. But, as you become a more experienced R user, you may want to start making your own functions.

For most people, the idea of making your first function comes when you realize you are copying and pasting code over and over. Maybe you’re doing the same data wrangling on multiple data frames. Maybe you’re making a nearly identical graph several times.

The initial impetus to make a function is usually that it is annoying to have to copy code multiple times. And, it becomes particularly annoying when, say, you realize that the graph you make 10 times using 10 copies of your code is just slightly off, forcing you to go back and make 10 separate changes to your code.

Making your own functions solves these two problems for you: you no longer have to copy your code 10 times and, if you do make any updates to your code, you make them in just one place.

My experience doing custom training with organizations transitioning to R is that learning about user-defined functions comes in two stages: 1) the realization that making functions could improve your code, and 2) understanding of how to make user-defined functions.

Having been asked over and over about user-defined functions, I decided to make a short video to demonstrate how they work (in that sense, this video is helping me to avoid repeating myself — a central goal of functions!). I’ve used a small dataset on school enrollment in five Western states and given myself the hypothetical task of creating a report on the largest schools in these states. As you’ll see in the video, I go from copying code multiple times to making a function that generates a table with the top X number of schools in each state.

If you like what you see and want to move your organization to R, please check out my custom training services. I’ve worked with organizations from across the country to move to R and become more efficient with their R programming by doing things like making functions.