Terms of a sum in a R expression

后端 未结 2 1851
佛祖请我去吃肉
佛祖请我去吃肉 2021-01-21 13:30

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 t

2条回答
  •  旧巷少年郎
    2021-01-21 13:52

    Try recursively parsing the expression:

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

    giving:

    [[1]]
    a
    
    [[2]]
    b * c
    
    [[3]]
    d
    
    [[4]]
    e * (f + g)
    

提交回复
热议问题