splice in a bquote in R
metaprogramming, r
Solution
This is an interesting question. After playing with things a bit, this is all I could come up with for your particular example.
> b <- quote(5 + 4)
> b[[2]] <- bquote(6 - .(b[[2]]))
> b
6 - 5 + 4
> eval(b)
[1] 5
Unfortunately, this may be hard to generalize, given the fact that you have to take into account the order of evaluation, etc.
Problem
Say that I'm building up an expression with R's backquote operator `bquote`, and I'd like to "splice" in a list at a specific position (that is, lose the outer parenthesis of the list). For example, I have the expression "5+4", and I'd like to prepend a "6-" to the beginning of it, without using string operations (that is, while operating entirely on the symbol structures). So: ``` > b = quote(5+4) > b 5 + 4 > c = bquote(6-.(b)) > c 6 - (5 + 4) > eval(c) [1] -3 ``` I would like that to return the evaluation of "6-5+4", so 5. In common lisp, the backquote "`" operator comes with a splice operator ",@", to do exactly this: ``` CL-USER> (setf b `(5 + 4)) (5 + 4) CL-USER> (setf c `(6 - ,@b)) (6 - 5 + 4) CL-USER> (setf c-non-spliced `(6 - ,b)) (6 - (5 + 4)) CL-USER> ``` I tried using .@(b) in R, but that didn't work. Any other ideas? And to restate, I do not want to resort to string manipulation.