4 Understanding the tools you’ll use: Functions

 

This chapter covers

  • Repeating operations with functions
  • The boundaries of where things are defined (scope)
  • Messages, warnings, and errors, and how to deal with them
  • Testing that your code does what you think it does

The true power of a programming language arises when you can tell the computer to do something and that request is simpler than just doing the work ourselves. Any time you want to calculate something more than once, it’s potentially a good idea to wrap the code up into a meaningful expression that can be reevaluated with a different (or even the same) input.

You’ll quickly see that functions are the standard method of achieving this goal in R. Once errors inevitably arise, you’ll also see how to manage things that don’t go according to plan.

4.1 Functions

A function (in programming) refers to a series of defined operations or routines that achieves some task, usually involving data, that produces some result. Functions can have input data (or not) and produce output data (or not) or perform some action. Functions may also define or use more data if the data is defined by the function itself (for example, constant numbers or values).

In R, functions are handled in the same way that data is — stored with a variable name — and can be sent as input to other functions. Saving the operations in a named function (the body of a function) has many advantages, including the following:

4.1.1 Under the hood

4.1.2 Function template

4.1.3 Arguments

4.1.4 Multiple arguments

4.1.5 Default arguments

4.1.6 Argument name matching

4.1.7 Partial matching

4.1.8 Scope

4.2 Packages

4.2.1 Installing packages

4.2.2 How does R (not) know about this function?

4.2.3 Namespaces

4.3 Messages, warnings, and errors, oh my!

4.3.1 Creating messages, warnings, and errors

4.3.2 Diagnosing messages, warnings, and errors

4.4 Testing

4.5 Project: Generalizing a function

4.6 Try it yourself

Terminology

Summary