I have been reading Hadley Wickham's Advanced R in the past couple of weeks and one particular concept has caught my attention which I would be grateful if you could provide me with an explanation:
The evaluation environment is slightly different for default and user supplied arguments, as default arguments are evaluated inside the function.
and the following example is presented by the book:
h05 <- function(x = ls()) {
a <- 1
x
}
# ls() evaluated inside h05:
h05()
#> [1] "a" "x"
# ls() evaluated in global environment:
h05(ls())
#> [1] "h05"
Here it is quite clear that the when the user provide ls()
as a value to argument x it is evaluated in the global environment. However in the following example when we provide 2 values for x
and y
it does not affect their value in the global environment, despite the fact they are being evaluated there:
y <- 6
x <- 5
f1 <- function(x, y) {
x*2 + y
}
f1(x = 4, y = 12)
I would like to know what I am missing here and whether the aforementioned rule only holds true when we define and argument in terms of other arguments within a function call.
Any explanation in much appreciated.