I have been reading Hadley Wickham's Advanced R in order to gain a better understanding of the mechanism or R and how it works behind the scene. I have so far enjoyed and everything is quite clear, there is one question that occupy s my mind for which I have not yet found an explanation. I am quite familiar with the scoping rules of R which determines how values are assigned to FREE VARIABLES, However I have been grappling with the idea that 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)
I normally throws and error cause 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:
f1 <- function(x = 2, y) {
y <- 4
x*2 + y
}
f1(x = 3)
Thank you very much in advance
You have specified an argument y
for the function, but not providing any value when asked for a value in return. So this will work
f1(x = 3, y)
[1] 10
Here it takes y
your defined variable as an input for the second argument which incidentally is also named y and returns a value.
even this will also work. As you have defined a default value to this function
y1 <- 4
f1 <- function(x = 2, y= y1) {
x*2 + y
}
f1(x=3)
#> [1] 10
f1(x = 3, 5)
#> [1] 11
Created on 2021-05-03 by the reprex package (v2.0.0)
If you want to evaluate any function without giving any value for any argument, you have to define that in function itself.