gpt4 book ai didi

r - R 表达式中的求和项

转载 作者:行者123 更新时间:2023-12-02 14:55:12 24 4
gpt4 key购买 nike

给定一个表示项总和的 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com