Chapter 5Writing Functions and Scripts
Functions and scripts are two methods by which we can do repetitive tasks easily. They have similar goals, but they operate in different ways. In our work, we use both, and every data cleaning project will require that you create functions or scripts – probably both but almost certainly scripts, since R already has lots of functions to perform lots of necessary tasks – and, of course, we have met many of these in earlier chapters.
Writing functions is more difficult than writing scripts because there are strict rules about what functions can do and how they operate. In contrast, a script is very often just a saved set of commands that you typed in to accomplish a particular task. Of course, the commands you type in are themselves calls to R's built-in functions, and sometimes you need to do something for which no function has been written. In that case, you may have to write your own. In this chapter, we describe what functions and scripts do and their relative strengths.
5.1 Functions
A function is a special R object. If you have made it this far in the book, you probably know a lot about how functions work. But we want to repeat some of the details here, to make clear the important points that will come up when you start writing your own. A function's text starts with the reserved word function
, then it has its list of arguments inside parentheses, and then it has the body of the function enclosed in braces. If the body is only one line, ...
Get A Data Scientist's Guide to Acquiring, Cleaning, and Managing Data in R now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.