kevin
kevin

Reputation: 174

R functions: why expressions can't be evaluated within return?

f=function(x){return(list(y=x, z = y))}; f(1)

I wonder why the above function does not work. Thank you very much!

Upvotes: 1

Views: 71

Answers (1)

Gwang-Jin Kim
Gwang-Jin Kim

Reputation: 9865

It doesn't work, because the arguments of the function list cannot "see" each other, so the statement z = y cannot "see" y = x.

This remembers me of the difference of let and let* in Lisp languages. let does local assignments for local variables. They can't "see" each other. But let* makes the following assignments be able to "see" the previous assignments.

Why not doing:

f=function(x){y <- x; return(list(y = x, z = y))}; f(1)

Upvotes: 2

Related Questions