Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the logic of this function in R?

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?

like image 983
Song Lee Avatar asked Feb 07 '19 08:02

Song Lee


People also ask

How do I check logic in R?

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.

How do you write a logical function in R?

& and && indicate logical AND and | and || indicate logical OR. The shorter form performs elementwise comparisons in much the same way as arithmetic operators.

What does != In R mean?

greater than or equal to. == exactly equal to. != not equal to.


1 Answers

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.

like image 94
digEmAll Avatar answered Oct 18 '22 17:10

digEmAll