Functions as Arguments
Many functions in R can take other functions as arguments. For example, many modeling functions accept an optional argument that specifies how to handle missing values; this argument is usually a function for processing the input data.
As an example of a function that takes another function as an
argument, let’s look at sapply
. The
sapply
function iterates through each element in a vector, applying another
function to each element in the vector and returning the results. Here is
a simple example:
> a <- 1:7 > sapply(a, sqrt) [1] 1.000000 1.414214 1.732051 2.000000 2.236068 2.449490 2.645751
This is a toy example; you could have
calculated the same quantity with the expression sqrt(1:7)
. However, there are many useful
functions that don’t work properly on a vector with more than one element;
sapply
provides a simple way to extend
such a function to work on a vector. Related functions allow you to
summarize every element in a data structure or to perform more complicated
calculations. See Summarizing Functions for information
on related functions.
Anonymous Functions
So far, we’ve mostly seen named functions in R. However, because functions are just objects in R, it is possible to create functions that do not have names. These are called anonymous functions. Anonymous functions are usually passed as arguments to other functions. If you’re new to functional languages, this concept might seem strange, so let’s start with a very simple example.
We will define a function ...
Get R in a Nutshell, 2nd Edition 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.