Chapter 11 Functions

ds4psy: (11) Functions

In the previous chapters, we have been using all kinds of functions to solve specific tasks. For instance, we have learned to load, explore, and transform data tables into various forms and formats. To achieve this, we have used various functions from base R (R Core Team, 2019) and various tidyverse packages (Wickham, 2017). An important next step is learning to program, which essentially consists in creating our own functions.

Writing functions is a key step in learning to program.

Figure 11.1: Writing functions is a key step in learning to program.

Writing your own functions changes how you interact with R. To put this step into perspective, consider the old proverb:

Give a man a fish, and you feed him for a day.
Teach a man to fish, and you feed him for a lifetime.

When applied to R, this means that the existing R functions and packages may serve you well for quite a while, but eventually you will want to write your own functions. As most analogies, likening learning R to fishing to feed oneself has its limitations. As we discussed in the introductory chapter, R provides a toolbox that comes with many different tools. Thus, learning to use the rich collection of existing functions is quite an accomplishment and enables you to address a wide variety of tasks. And just as you usually feel no need to design a new hammer whenever you want to hit a nail, there is nothing wrong with using existing functions, as long as they get the job done. In the long run, however, and as your analysis needs get more specific and demanding, acquiring a general skill (like programming) can be more useful than always searching for the tool that meets your current need (i.e., locating functions or packages that solve particular problems).

In this chapter, we will introduce the basics of writing new functions. As this frequently requires controlling the flow of information in our code, we will also learn how to use conditional statements. Together with Chapter 12 on Iteration, this will help us to create programs that allow abstracting and automating complex procedures.


R Core Team. (2019). R: A language and environment for statistical computing. Retrieved from

Wickham, H. (2017). tidyverse: Easily install and load the ’tidyverse’. Retrieved from