I'm studying about arguments in R functions, but I have some problem to understand the logic of it.
h <- function(a = 1, b = d){
d <- (a + 1)^2
c(a, b)
}
h()
# [1] 1 4
I expected the error message would be return because there is no value of b
.
d
is created under h
function but there is no code like b = d
which assign a value to b
in function h
.
However, the result is [1] 1 4
.
How were b
and d
linked?
To check if type of given vector is logical in R, call is. logical() function and pass the vector as argument to this function. If the given vector is logical, then is. logical() returns TRUE, or else, it returns FALSE.
& and && indicate logical AND and | and || indicate logical OR. The shorter form performs elementwise comparisons in much the same way as arithmetic operators.
greater than or equal to. == exactly equal to. != not equal to.
Default function arguments values are lazily evaluated in R (i.e. evaluated only when they're needed):
See the output of this code for an example :
printme <- function(name,x){cat('evaluating',name,'\n');x}
h <- function(a = printme('a',1), b = printme('b',d)){
cat('computing d...\n')
d <- (a + 1)^2
cat('d computed\n')
cat('concatenating a and b...\n')
c(a, b)
cat('a and b concatenated\n')
}
h()
Console output :
computing d...
evaluating a
d computed
concatenating a and b...
evaluating b
a and b concatenated
As you can see, d
is calculated before evaluating the default value of b
EDIT :
Furthermore, as correctly pointed out by @BrodieG in the comments, default arguments are evaluated in the function environment; in fact, in the example above, b
can be initialized to the value of variable d
that is defined inside the function environment.
Instead, when you specify a argument (without using the default), the expression that assigns the parameter is still lazily evaluated, but this time in the calling environment e.g. :
# same functions as above, but this time we specify the parameters in the call
h(a=printme('a',123),b=printme('d',d))
Console output :
computing d...
evaluating a
d computed
concatenating a and b...
evaluating d
Error in printme("d", d) : object 'd' not found
Note the error when argument b
is evaluated because d
cannot be found in the calling environment.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With