I have been reading Hadley Wickham's Advanced R in order to gain a better understanding of the mechanisms of R and how it works behind the scene. I have so far enjoyed it and everything is quite clear. There is one question that occupies my mind for which I have not yet found an explanation. I am quite familiar with the scoping rules of R which determine how values are assigned to FREE VARIABLES. However, I have been grappling with the question of why R cannot find the value of a formal argument through lexical scoping in the first case. Consider the following example:
y <- 4
f1 <- function(x = 2, y) {
x*2 + y
}
f1(x = 3)
It normally throws an error because I didn't assign a default value for argument y. However, if I create a local variable y in the body of the function it won't throw any error:
I also read in Professeur Matloff's book that arguments act like local variables, so that's why this question remains a mystery for me.
f1 <- function(x = 2, y) {
y <- 4
x*2 + y
}
f1(x = 3)
And also here there is no error and it is quite clear why:
y <- 2
f2 <- function(x = 2) {
x*2 + y
}
f2()
Thank you very much in advance.