Terms of a sum in a R expression

后端 未结 2 1935
佛祖请我去吃肉
佛祖请我去吃肉 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:48

    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)
    

提交回复
热议问题