r - R 表达式中的求和项

标签 r evaluation

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

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

我想检索总和的所有项的集合作为列表 的名称或表达式。所以在示例中,元素将是:a , b * c , de * f .

以下来自comment .

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.

是否有一种简单的方法可以继续,例如,使用 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/

相关文章:

JavaScript 后缀数学

c# - 空条件运算符 and !=

r - 如何提取拟合 nls 模型中使用的参数,以便在 do.call 的第二次拟合中使用

r - 是否可以在R中读取.wma声音文件?

r - 使用 DT - Shiny - R 根据其他列更改行的颜色

r - 如何cbind R中矩阵列表的所有行组合

string - 在 Prolog 中计算字符串

r - 插入 'facet_grid' ed 和 'grid.arrange' ed 图

c++ - if 语句如何在 C++ 中求值?

java - K近邻OpenCV算法