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 ex
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 to expr
. Then, when expr
's evaluation is forced in the body of system.time
, it is evaluated in the evaluation frame of the calling function. If system.time()
was called from the .GlobalEnv
, that is where any assignments that are a part of expr
will take place.
EDIT:
Here's an example showing that expr
is evaluated in the global environment if it is a supplied (but not a default) argument.
st2 <- function(expr = newVar <- 33){
expr
}
# Using the default argument -- eval and assignment
# within evaluation frame of the function.
st2()
newVar
Error: object 'newVar' not found
# Using a supplied argument -- eval and assignment
# within the calling function's evaluation frame (here .GlobalEnv)
st2(newVar <- 44)
newVar
# [1] 44