Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bewildering behavior of `substitute` in R

Guys, this drives me crazy.

This works as expected:

eobj <- substitute(obj <- list(a, b), list(a = 32, b = 33))
eval(eobj)
obj
[[1]]
[1] 32

[[2]]
[1] 33

Now, try this:

efun <- substitute(fun <- function() a+ b, list(a = 32, b = 33))
str(efun)
# language fun <- function() 32 + 33  
eval(efun)
fun
# function() a+ b

What is going on here? How on earth eval gets it hands on the original form of the expression?

like image 992
VitoshKa Avatar asked Nov 02 '10 14:11

VitoshKa


1 Answers

Cause when you print fun it's actually print source of function (see attributes(fun)) which isn't modify by substitute.

Notice that when you define a or b in global workspace function result are the same.

You can see actual code of function by body(fun).

Or compare:

print.function(fun, useSource=FALSE)
# function () 
# 32 + 33
print.function(fun, useSource=TRUE) # Which is default
# function() a+ b
like image 196
Marek Avatar answered Sep 21 '22 12:09

Marek