Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

splice in a bquote in R

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.

like image 475
Clayton Stanley Avatar asked Feb 20 '14 00:02

Clayton Stanley


Video Answer


1 Answers

You need to realize that R expressions are not stored with the infix order that their print method may lead you to believe:

> b = quote(5+4)
>  b[[1]]
`+`
> b = quote(5+4)
>  b[[2]]
[1] 5
> b = quote(5+4)
>  b[[3]]
[1] 4

Whereas the print method for language objects might make you think the the second argument to 6 -5 +4 is 6-5,....

> b2 <- bquote(6 - 5 + 4)
> b2[[1]]
`+`
> b2[[2]]
6 - 5

.... that is also an illusion. It really has a list structure. (I would have thought this would be expected by a Lisp user.)

> b2[[3]]
[1] 4
> b2[[2]][[1]]
`-`
> b2[[2]][[2]]
[1] 6
> b2[[2]][[3]]
[1] 5
like image 74
IRTFM Avatar answered Oct 19 '22 01:10

IRTFM