Mick Miod....
Mick Miod....

Reputation: 23

Why does r str changes evaluation

Using str() appears to change the evaluation why?

MWE:

f1 <- function(x, y = x) {
  str(y)
  x <- x + 1
  y }
 f1(1) # result is 1

f2 <- function(x, y = x) {
  x <- x + 1
  y }
 f2(1) # result is 2

Why does this happen? I tried to use pryr library to debug but can not see the references being updated.

Upvotes: 2

Views: 46

Answers (1)

Zheyuan Li
Zheyuan Li

Reputation: 73265

Lazy evaluation. It is about when y = x is evaluated. It is evaluated right before the first statement that uses y.

## f1
y <- x
str(y)  ## first use of y
x <- x + 1
y

## f2
x <- x + 1
y <- x
y  ## first use of y

Upvotes: 2

Related Questions