R表达式中的总和项 [英] Terms of a sum in a R expression

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

问题描述

给出一个R表达式,该表达式表示诸如和的项之和

Given a R expression which represents a sum of terms like

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

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

I would like to retrieve the set of all the terms of the sum as a list of names or expressions. So in the example, the elements would be: a, b * c, d and e * f.

以下内容来自评论.

项目本身可以包含+运算符,如

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

所以我们需要对R语言有一定的了解.

so we need some understanding of the R language.

是否有一种简单的方法来进行操作,例如使用 pryr 软件包中的call_tree?

Is there a simple way to proceed e.g., using call_tree of the pryr package?

推荐答案

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

You can use a recursive function to crawl the parse tree:

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表达式中的总和项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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