In programming language terminology,xis theformal argument(or
formal parameter) of the functionoddcount(). In the first function call in the
preceding example,c(1,3,5)is referred to as theactual argument. These
terms allude to the fact thatxin the function definition is just a placeholder,
whereasc(1,3,5)is the value actually used in the computation. Similarly, in
the second function call,c(1,2,3,7,9)is the actual argument.
1.3.1 Variable Scope.................................................
A variable that is visible only within a function body is said to belocalto that
function. Inoddcount(),kandnare local variables. They disappear after the
function returns:
oddcount(c(1,2,3,7,9))
[1] 4
n
Error: object 'n' not found
It’s very important to note that the formal parameters in an R function
are local variables. Suppose we make the following function call:
z <- c(2,6,7)
oddcount(z)
Now suppose that the code ofoddcount()changesx. Thenzwouldnotchange.
After the call tooddcount(),zwould have the same value as before. To eval-
uate a function call, R copies each actual argument to the corresponding
local parameter variable, and changes to that variable are not visible outside
the function.Scoping rulessuch as these will be discussed in detail in Chap-
ter 7.
Variables created outside functions areglobaland are available within
functions as well. Here’s an example:
f <- function(x) return(x+y)
y<-3
f(5)
[1] 8
Hereyis a global variable.
A global variable can be written to from within a function by using R’s
superassignment operator,<<-. This is also discussed in Chapter 7.
1.3.2 Default Arguments..............................................
R also makes frequent use ofdefault arguments. Consider a function defini-
tion like this:
g <- function(x,y=2,z=T) { ... }
Getting Started 9