Can somebody please explain what happens when an expression is evaluated in system.time? In particular, why are any variables that are declared in the expr argument visible in the global environment?
Here is a pared-down version of the innards of system.time that does nothing other than evaluating the expression that is passed to the function:
st <- function(expr){
expr
}
st(aa <- 1)
aa
[1] 1
Clearly the effect of this is that it creates the variable aa in the global environment. This baffles me, since I thought that assigning a variable inside a function makes it local in scope.
What happens here?
It is because supplied arguments are evaluated in the evaluation frame of the calling function (as described in Section 4.3.3 of the R Language Definition document).
The expression wrapped by the user in
system.time()is a supplied argument which gets matched positionally toexpr. Then, whenexpr‘s evaluation is forced in the body ofsystem.time, it is evaluated in the evaluation frame of the calling function. Ifsystem.time()was called from the.GlobalEnv, that is where any assignments that are a part ofexprwill take place.EDIT:
Here’s an example showing that
expris evaluated in the global environment if it is a supplied (but not a default) argument.