问题描述
我知道我可以使用substitute
函数在R中创建一个表达式树.假设我生成了以下表达式树:
I know that I can create an expression tree in R using the substitute
function. Let's say that I generate the following expression tree:
expT <- substitute(a+(2*b+c))
是否可以在R中可视化表达式树,从而生成类似以下内容的
Is it possible to visualize the expression tree in R, producing something like:
我知道(
也是R中的一个函数,但是我想在绘图中忽略它.
I know that (
is also a function in R, but I would like to omit that in the plot.
推荐答案
这是一种利用功能utils::getParseData
并从为 parser
程序包,并使用igraph
进行显示.链接的函数几乎可以完成您想要的操作,但是getParseData
函数返回的数据具有空白节点,这些节点的叶子上带有数值/符号/运算符等.如果您尝试解析函数或三元表达式或更复杂的事物,这是很有意义的.
Here is an approach taking advantage of the function utils::getParseData
and borrowing from a function written for the parser
package and using igraph
for the visuals. The linked function almost does what you wanted, but the data returned by the getParseData
function has blank nodes with the numerical values/symbols/operators etc. on the leaves. This makes sense if you try to parse functions or ternary expressions or more complicated things.
此功能只是根据解析数据创建边缘列表.
This function simply creates an edgelist from the parse data.
## 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)
}
下一个函数通过删除所有'(){}'和剩余的空白来折叠解析树.想法是首先将所有标签在树中上移一层,然后修剪叶子.最后,通过创建/销毁边缘来消除嵌套表达式('(){}')中的所有间隙.我将边缘涂成蓝色,除去了从括号/括号中嵌套的层次.
The next function collapses the parse tree by removing all the '(){}' and remaining gaps. The idea is to first move all the labels up one level in the tree, then clip the leaves. And finally all the gaps from nested expressions ('(){}') are removed by creating/destroying edges. I colored the edges blue where levels of nesting from brackets/braces were removed.
## 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)
}
一个例子,嵌套的表达式稍微多一些.动画显示了原始树是如何折叠的.
An example, slightly more nested expression. The animation shows how original tree is collapsed.
## 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)
这篇关于在R中绘制表达式树的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!