Coolwater Coolwater - 1 year ago 69
R Question

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

This code reveals that

doesn't yet look up
before it's called.

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

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

Answer Source

In Common Lisp this would look like:

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

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.