2.2 Function basics

Non-primitive functions may also be assigned using the assignment operator along with the function called function. As an example, the follwing code creates a function called BMI to calculate an individual’s body mass index given their weight and height measurements. We’ll walkthrough the syntax of this call, to illustrate the components of typical R functions.

All non-primitive R functions have four main components: a symbol, a body, formal arguments, and an enclosing environment. A description these components is shown in Table 2.3.

Table 2.3: Components of non-primative R functions
Component Name Component Description
symbol The name to which a function is assigned
body Code within a function performing one or operations
formals the arguments used to call the function
environment the mapping of the location(s) of the function’s variables

Determining a functions’ symbol is usually trivial - the other components can be determined using the body(), formals(), and environment() functions provided by the base package. Using these functions to retreive information about BMI first requires that BMI be defined in the current workspace. This is accomplished by simply pasting the above code into the R console.

Often, when a function is created it’s body is contained within curly brackets. In R, curly brackets are used encapsulate multiple lines of code that are used together to obtain a result. For the function BMI, the body does not span multiple lines - thus the curly brackets we’re not required in this instance.

2.2.1 Evaluating functions

Evaluating a function is accomplished by calling the function’s symbol and providing values for the formal arguments. The following call returns a value for the function BMI based on values provided for weight_kg and height_m. Note that values are provided for formal arguments inside parentheses and are separated by commas.

When the BMI function was created no default values were set for the formal arguments. As result, R will return an error if either of the formal arguments are missing. If instead we had created BMI as follows, no error would result from missing arguments, as the default values would then be used.

Finally, when evaluating functions values can provided for the formal arguments without explicitly specifying which value is assigned to which argument. When specified this way, R uses positional matching for all formal arguments according to the order used when the function was defined.

Functions are a fundamental building block of R and writing functions is a core activity of an R programmer. It represents the key step of the transition from a mere “user” to a developer who creates new functionality for R. As a result, its important to turn your existing, informal knowledge of functions into a rigorous understanding of what functions are and how they work. A few additional resources that can help you get to the next step of understanding functions include: