Default arguments vs User-defined arguments

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.

the x=4 portion has no effect on the global environment, it is merely constructing a call.
If you go up to your first example
ho5(x=ls())
would not be expected to give you a variable x in the global environment, it merely constructs the call so that in the function scope x can take a value.

Thank you for your answer. I would like to ask where are those user defined arguments evaluated. because in the case of following call

f1(x = 4, y <- x)

the value of y in the global environment changes as the second promise is evaluated there. but I would precisely like to know where this x = 4 is evaluated?

I think that the answer is that your last example is equivalent to

f1(x = 4, y=y <- x)

my mental model is that every param is evaluated as its offered to the function call.
so here we now we are dealing with a number 4, this has no effect on the global environment and the function scope is setup with an x object as per definition and the value is just that 4.
we are dealing with an assignment of x to y, this has an effect on the global environment because thats where we are, also the value is going to be used for the function scope we are setting up.
consider


y <- 6
x <- 5

f1 <- function(x, y) {
  x*2 + y
}

f1(x = 4, y= z <- x) # here we assign to z
x
y
z
1 Like

Thank you very much for taking time out to answer my question, I really appreciate it and your answer was quite helpful.

This topic was automatically closed 21 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.