Coolwater
Coolwater

Reputation: 723

How to replace symbols by their value in a R function body

This code reveals that f doesn't yet look up q before it's called.

q <- 2
f <- function(x) q + x
f

I want to tell R which symbols in the body to look up right away (in this case list("q")) and have it modify f accordingly. How can it be done?

Upvotes: 0

Views: 97

Answers (3)

Clayton Stanley
Clayton Stanley

Reputation: 7784

In Common Lisp this would look like:

CL-USER> (defparameter q 4)
Q
CL-USER> (let ((bar q))
            (defmacro f (x)
               `(+ ,bar ,x)))
F
CL-USER> (macroexpand-1 `(f 4))
(+ 4 4)
T

In R this could look like:

> q = 2
> f = eval(bquote(function(x) .(q) + x))
> f
function (x) 
2 + x
> 

Since R is interpreted, eval is par for the course there. With Common Lisp, if you do not want to use eval, you can go with a compile-time macro that carries along with it a hard-coded value for 'q, so that every time it is used in code at that point on it refers to the value of 'q at creation time of the macro.

Upvotes: 5

Gregory Demin
Gregory Demin

Reputation: 4846

You could use something like this:

f_generator = function(q){
    q
    function(x){
        q + x
    }
}


f2 = f_generator(2)
f3 = f_generator(3)

f2(1)
# 3
f3(1)
# 4

Upvotes: 2

IRTFM
IRTFM

Reputation: 263411

Actually you are wrong about what happens when you make an assignment for a token of the value of function. Take a look at this:

> environment(f)$q
[1] 2

Some of the base R function keep values hidden away in the environments of the returned objects. The two that come to mind are ecdf and splinefun.

Upvotes: 2

Related Questions