R 表达式中的求和项

Terms of a sum in a R expression

给定一个表示项总和的 R 表达式,例如

expr <- expression(a + b * c + d + e * f)

我想检索总和的所有项的集合作为列表 的名称或表达式。因此在示例中,元素将是:ab * cde * f

以下来自

The tems could themselves contain a + operator as in

expression(a + b * c + d + e * (f + g))

so we need some understanding of the R language.

是否有一种简单的方法可以继续,例如,使用 pryr 包的 call_tree

尝试递归解析表达式:

getTerms <- function(e, x = list()) {
  if (is.symbol(e)) c(e, x)
  else if (identical(e[[1]], as.name("+"))) Recall(e[[2]], c(e[[3]], x))
  else c(e, x)
}

expr <- expression(a + b * c + d + e * (f + g))
getTerms(expr[[1]])

给予:

[[1]]
a

[[2]]
b * c

[[3]]
d

[[4]]
e * (f + g)

您可以使用递归函数来爬取解析树:

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)