Coolwater Coolwater - 8 months ago 48
R Question

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?

Answer

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.