在R中绘制表达式树

时间:2015-10-29 16:09:50

标签: r plot expression-trees

我知道我可以使用substitute函数在R中创建表达式树。让我们说我生成以下表达式树:

expT <- substitute(a+(2*b+c))

是否可以在R中可视化表达式树,产生如下内容:

Expression Tree

我知道(也是R中的一个函数,但我想在图中省略它。

4 个答案:

答案 0 :(得分:11)

这是一种利用函数utils::getParseData并借用为parser package 编写的函数并使用igraph作为视觉效果的方法。链接函数几乎可以执行您想要的操作,但getParseData函数返回的数据在叶子上具有空值节点,其中包含数值/符号/运算符等。如果您尝试解析函数或三元表达式或更复杂的事情,这是有道理的。

此函数只是从解析数据中创建一个edgelist。

## https://github.com/halpo/parser/blob/master/R/plot.parser.R
## Modified slightly to return graph instead of print/add attr
parser2graph <- function(y, ...){
    y$new.id <- seq_along(y$id)
    h <- graph.tree(0) + vertices(id = y$id, label= y$text)
    for(i in 1:nrow(y)){
        if(y[i, 'parent'])
            h <- h + edge(c(y[y$id == y[i, 'parent'], 'new.id'], y[i, 'new.id']))
    }
    h <- set_edge_attr(h, 'color', value='black')
    return(h)
}

下一个函数通过删除所有'(){}'和剩余的间隙来折叠解析树。我们的想法是首先将所有标签向上移动到树中的一个级别,然后剪切树叶。最后,通过创建/销毁边缘来移除嵌套表达式('(){}')中的所有间隙。我将边缘涂成蓝色,从括号/大括号中除去嵌套水平。

## Function to collapse the parse tree (removing () and {})
parseTree <- function(string, ignore=c('(',')','{','}'), ...) {
    dat <- utils::getParseData(parse(text=string))
    g <- parser2graph(dat[!(dat$text %in% ignore), ])
    leaves <- V(g)[!degree(g, mode='out')]                             # tree leaves
    preds <- sapply(leaves, neighbors, g=g, mode="in")                 # their predecessors
    vertex_attr(g, 'label', preds) <- vertex_attr(g, 'label', leaves)  # bump labels up a level
    g <- g - leaves                                                    # remove the leaves
    gaps <- V(g)[!nchar(vertex_attr(g, 'label'))]                      # gaps where ()/{} were
    nebs <- c(sapply(gaps, neighbors, graph=g, mode='all'))            # neighbors of gaps
    g <- add_edges(g, nebs, color='blue')                              # edges around the gaps
    g <- g - V(g)[!nchar(vertex_attr(g, 'label'))]                     # remove leaves/gaps
    plot(g, layout=layout.reingold.tilford, ...)
    title(string, cex.main=2.5)
}

一个例子,稍微嵌套的表达式。动画显示了原始树的折叠方式。

## Example string
library(igraph)
string <- "(a/{5})+(2*b+c)"

parseTree(string,  # plus some graphing stuff
          vertex.color="#FCFDBFFF", vertex.frame.color=NA,
          vertex.label.font=2, vertex.label.cex=2.5,
          vertex.label.color="darkred", vertex.size=25,
          asp=.7, edge.width=3, margin=-.05)

enter image description here

答案 1 :(得分:5)

以下内容大部分都在那里。它模仿pryr:::tree以递归方式检查调用树,然后分配data.tree个节点。我更喜欢igraph,但它不能容忍重复的节点名称(例如+出现两次)。我也无法让dendrogram标记除根之外的任何分支。

#install.packages("data.tree")
library(data.tree)

make_tree <- function(x) {
  if (is.atomic(x) && length(x) == 1) {
    as.character(deparse(x)[1])
  } else if (is.name(x)) {
    x <- as.character(x)
    if (x %in% c("(", ")")) {
      NULL
    } else {
      x
    }
  } else if (is.call(x)) {
    call_items <- as.list(x)
    node <- call_items[[1]]
    call_items <- call_items[-1]
    while (as.character(node) == "(" && length(call_items) > 0) {
      node <- call_items[[1]]
      call_items <- call_items[-1]
    }
    if (length(call_items) == 0) 
      return(make_tree(node))
    call_node <- Node$new(as.character(node))
    for (i in 1:length(call_items)) {
      res <- make_tree(call_items[[i]])
      if (is.environment(res))
        call_node$AddChildNode(res)
      else
        call_node$AddChild(res)
    }
    call_node
  } else
    typeof(x)
}

tree <- make_tree(quote(a+(2*b+c)))
print(tree)
plot(as.dendrogram(tree, edgetext = T), center = T, type = "triangle", yaxt = "n")

这给出了合理的文本输出:

      levelName
1 +            
2  ¦--a        
3  °--+        
4      ¦--*    
5      ¦   ¦--2
6      ¦   °--b
7      °--c    

和图形。乘法符号不会出现在中间树节点中(我无法弄清楚原因),但除此之外,我认为这可以完成这项工作。 call tree plot

答案 2 :(得分:3)

这里有一些代码和结果可能会有所帮助,而且至少能够“走”“解析树”:

> parse( text="a+(2*b+c)")
expression(a+(2*b+c))
> parse( text="a+(2*b+c)")[[1]]
a + (2 * b + c)
> parse( text="a+(2*b+c)")[[1]][[1]]
`+`
> parse( text="a+(2*b+c)")[[1]][[2]]
a
> parse( text="a+(2*b+c)")[[1]][[3]]
(2 * b + c)
> parse( text="a+(2*b+c)")[[1]][[4]]
Error in parse(text = "a+(2*b+c)")[[1]][[4]] : subscript out of bounds
> parse( text="a+(2*b+c)")[[1]][[3]][[1]]
`(`
> parse( text="a+(2*b+c)")[[1]][[3]][[2]]
2 * b + c
> parse( text="a+(2*b+c)")[[1]][[3]][[2]][[1]]
`+`
> parse( text="a+(2*b+c)")[[1]][[3]][[2]][[2]]
2 * b
> parse( text="a+(2*b+c)")[[1]][[3]][[2]][[3]]
c
> parse( text="a+(2*b+c)")[[1]][[3]][[2]][[2]][[1]]
`*`
> parse( text="a+(2*b+c)")[[1]][[3]][[2]][[2]][[2]]
[1] 2
> parse( text="a+(2*b+c)")[[1]][[3]][[2]][[2]][[3]]
b

我以为我曾经看过Thomas-Lumley或Luke Tierney在R-help或r-devel中发布过这样做的帖子,但到目前为止还未能找到它。我确实找到了@ G.Grothendieck的帖子,它以编程方式拉开了你可能构建的解析树:

 e <- parse(text = "a+(2*b+c)") 
my.print <- function(e) { 
  L <- as.list(e) 
  if (length(L) == 0) return(invisible()) 
  if (length(L) == 1) 
     print(L[[1]]) 
     else sapply(L, my.print) 
return(invisible()) } 
my.print(e[[1]])
#----- output-----
`+`
a
`(`
`+`
`*`
[1] 2
b
c

答案 3 :(得分:2)

这绝对是可能的,但我不知道现有的功能。那就是说,这是一个很好的练习。请查看Walking the AST with recursive functions(并阅读整章),了解有关如何在表达式树上进行操作的基本说明。

由此,其余的“相对”直截了当:

  • 对于每个节点,确定要打印的符号。
  • 维护当前节点的(相对)坐标。在递归表达式时,此坐标会根据您的操作进行更新;例如,您知道函数调用的参数需要在其调用之下居中,因此您可以相应地更新y坐标,然后根据有多少参数计算x。运营商只是一个特例。

最后,你可以使用它们的坐标旁边的符号来相对于彼此绘制它们。