R表达式中和的项

R表达式中和的项,r,evaluation,R,Evaluation,给定一个R表达式,它表示如下项的和 expr尝试递归解析表达式: 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)) getTer

给定一个R表达式,它表示如下项的和


expr尝试递归解析表达式:

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]])

您可以使用递归函数对解析树进行爬网:

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)

foo也许我的问题还不够清楚:TEM本身可能包含一个
+
运算符,如
表达式(a+b*c+d+e*(f+g))
,所以我们需要对R语言有一些了解。@Yves,那么你也应该在问题中给出这个例子。我们已经修改以回应评论。谢谢你这个漂亮的答案(+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)