剪接R中的bquote [英] splice in a bquote in R

查看:225
本文介绍了剪接R中的bquote的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我正在使用R的反引号运算符bquote建立一个表达式,并且我想在列表中的特定位置拼接"(即,失去列表的外部括号). /p>

例如,我有一个表达式"5 + 4",并且我想在它的开头加上一个"6-",而不使用字符串操作(也就是说,完全在符号结构上进行操作)

所以:

>   b = quote(5+4)
>   b
5 + 4
>   c = bquote(6-.(b))
>   c
6 - (5 + 4)
>   eval(c)
[1] -3

我希望返回"6-5 + 4"的评估结果,所以5.

在常见的Lisp中,反引号`"运算符带有一个拼接运算符,@",可以做到这一点:

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> 

我尝试在R中使用.@(b),但这没有用.还有其他想法吗?重申一下,我不想求助于字符串操作.

解决方案

这是一个有趣的问题.在玩了一点之后,这就是我为您的特定示例所能想到的全部内容.

> b <- quote(5 + 4)
> b[[2]] <-  bquote(6 - .(b[[2]]))
> b
6 - 5 + 4
> eval(b)
[1] 5

不幸的是,鉴于您必须考虑评估顺序等事实,这可能很难一概而论.

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.

解决方案

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.

这篇关于剪接R中的bquote的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆