> f(3,2)
[1] 1
> g <- function(h,a,b) h(a,b)
> g(f1,3,2)
[1] 5
> g(f2,3,2)
[1] 1
And since functions are objects, you can loop through a list consisting of
several functions. This would be useful, for instance, if you wished to write a
loop to plot a number of functions on the same graph, as follows:
> g1 <- function(x) return(sin(x))
> g2 <- function(x) return(sqrt(x^2+1))
> g3 <- function(x) return(2*x-1)
> plot(c(0,1),c(-1,1.5)) # prepare the graph, specifying X and Y ranges
> for (f in c(g1,g2,g3)) plot(f,0,1,add=T) # add plot to existing graph
The functionsformals()andbody()can even be used as replacement
functions. We’ll discuss replacement functions in Section 7.10, but for now,
consider how you could change the body of a function by assignment:
> g <- function(h,a,b) h(a,b)
> body(g) <- quote(2*x+3)
>g
function (x)
(^2) *x+3
g(3)
[1] 9
The reasonquote()was needed is that technically, the body of a func-
tion has the class"call", which is the class produced byquote(). Without the
call toquote(), R would try to evaluate the quantity (^2) x+3.Soifxhad been
defined and equal to 3, for example, we would assign 9 to the body ofg(),
certainly not what we want. By the way, sinceand+are functions (as dis-
cussed in Section 2.4.1), as a language object, (^2) *x+3is indeed a call—in fact,
it is one function call nested within another.
7.6 Environment and Scope Issues...............................................
A function—formally referred to as aclosurein the R documentation—
consists not only of its arguments and body but also of itsenvironment. The
latter is made up of the collection of objects present at the time the function
is created. An understanding of how environments work in R is essential for
writing effective R functions.
R Programming Structures 151