Skip to content
Prev 305811 / 398506 Next

[newbie] aggregating table() results and simplifying code with loop

Hello,
Inline
Em 18-09-2012 23:42, Davide Rizzo escreveu:
A function's arguments are defined, surprise!, in the function's 
definition. See R-intro chap. 10 and R-Inferno chap. 6.
Example:

f <- function(x){
     y <- 2*x + 1
     y
}

x <- 1
f(2)  # returns 5

This is because the 'x' outside the function is not the same as the 'x' 
inside the function. In the function definition I can choose any name I 
want, and then use that name in the function's body.
(Actually it's a bit more complicated because if a function uses a 
variable not passed to nor defined in the function, R will look for it 
in the caller's environment, and goes up until the global environment. 
It throws an error only if it's nowhere to be found.)

Chap. 6 of the R-inferno is about global assignments, also saying that 
in R if a function changes its arguments the modified version has 
nothing to do with the argument's value outside the function. Uunless 
it's returned, on exit this new value is lost. This is the case of 
example 1, variable 'x'.

This behavior is very usefull because it means that side effects are 
unlikely to occur. That's what P. Burns is talking about when he says 
that "Surprise in movies and novels is good. Surprise in computer code 
is bad." To understand a function look at the way it is called, and to 
what happens in it. Forget almost all of the rest, the exception being 
what is passed to it.

Finally, like with everything, it takes some time to be comfortable with 
R. And practice.

Have fun.

Rui Barradas