As remarked at several points in this book, the purpose of the R function function()
is to create functions. For instance, consider this code:
inc <- function(x) return(x+1)
It instructs R to create a function that adds 1 to its argument and then assigns that function to inc
. However, that last step—the assignment—is not always taken. We can simply use the function object created by our call to function()
without naming that object. The functions in that context are called anonymous, since they have no name. (That is somewhat misleading, since even nonanonymous functions only have a name in the sense that a variable is pointing to them.)
Anonymous functions can be convenient if they are short one-liners and are called by another function. Let’s go back to our example of using apply
in Section 3.3:
> z [,1] [,2] [1,] 1 4 [2,] 2 5 [3,] 3 6 > f <- function(x) x/c(2,8) > y <- apply(z,1,f) > y [,1] [,2] [,3] [1,] 0.5 1.000 1.50 [2,] 0.5 0.625 0.75
Let’s bypass the middleman—that is, skip the assignment to f
—by using an anonymous function within our call to apply()
, as follows:
> y <- apply(z,1,function(x) x/c(2,8)) > y [,1] [,2] [,3] [1,] 0.5 1.000 1.50 [2,] 0.5 0.625 0.75
What really happened here? The third formal argument to apply()
must be a function, which is exactly what we supplied here, since the return value of function()
is a function!
Doing things this way is often clearer than defining the function externally. Of course, if the function is more complicated, that clarity is not attained.