What is the logic of this function in R?

  • A+
Category:Languages

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?

 


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.

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: