匹配R中的解析表达式

时间:2014-01-23 19:26:48

标签: r expression

给定一个符号或语言对象列表,搜索包含的最佳方法是什么?

例如,请考虑以下示例:

> a = list(substitute(1 + 2), substitute(2 + 3))
> substitute(1 + 2) %in% a
Error in match(x, table, nomatch = 0L) : 
  'match' requires vector arguments
> a == substitute(1 + 2)
[1]  TRUE FALSE
Warning message:
In a == substitute(1 + 2) :
  longer object length is not a multiple of shorter object length

第二种方法似乎有效,但我不确定警告的含义。

另一个想法是使用deparse然后比较字符,但当解析的表达式足够长以超过width.cutoff中的deparse时,这会变得复杂。

1 个答案:

答案 0 :(得分:0)

不起诉为什么你需要这样做但你可以使用identical进行比较。但是,由于identical仅比较两个参数,因此您必须循环遍历列表,最好使用lapply ...

lapply( a , function(x) identical( substitute(1 + 2) , x ) )
#[[1]]
#[1] TRUE

#[[2]]
#[1] FALSE

或者类似地,您仍然可以使用==。检查substitute(1 + 2)会将其显示为长度为3的language个对象,而您的列表a显然长度为2,因此会对向量回收发出警告。因此,您只需循环遍历列表中的元素即可:

lapply( a , `==` , substitute(1 + 2) )
#[[1]]
#[1] TRUE

#[[2]]
#[1] FALSE