Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
340 views
in Technique[技术] by (71.8m points)

evaluation - Terms of a sum in a R expression

Given a R expression which represents a sum of terms like

expr <- expression(a + b * c + d + e * 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.

The following comes from a 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.

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...