给定一个表示项总和的 R 表达式,例如
expr <- expression(a + b * c + d + e * f)
我想检索总和的所有项的集合作为列表
的名称或表达式。所以在示例中,元素将是:a
, b * c
, d
和 e * f
.
以下来自comment .
The tems could themselves contain a
+
operator as inexpression(a + b * c + d + e * (f + g))
so we need some understanding of the R language.
是否有一种简单的方法可以继续,例如,使用 call_tree
pryr 包?
最佳答案
您可以使用递归函数来爬取解析树:
foo <- function(x) {
if (is.call(x)) y <- as.list(x) else return(x)
#stop crawling if not a call to `+`
if (y[[1]] != quote(`+`)) return(x)
y <- lapply(y, foo)
return(y[-1]) #omit `+` symbol
}
expr1 <- expression(a + b * c + d + e * f)
unlist(foo(expr1[[1]]))
#[[1]]
#a
#
#[[2]]
#b * c
#
#[[3]]
#d
#
#[[4]]
#e * f
expr2 <- expression(a + b * c + d + e * (f + g))
unlist(foo(expr2[[1]]))
#[[1]]
#a
#
#[[2]]
#b * c
#
#[[3]]
#d
#
#[[4]]
#e * (f + g)
关于r - R 表达式中的求和项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53300717/