这篇关于 R 中可折叠树的文章激励了我
http://bl.ocks.org/mbostock/4339083
我正在尝试使用这样的玩具数据集重现相同的示例
ID Car Bus Train Feedback_Car Feedback_Bus Feedback_Train
23433 Yes Yes Yes Toyota GreyHound Amtrak
可以表示为如下可折叠树
我想知道是否有人可以帮助我使用上面的这个玩具数据集重现这个概念(可折叠树),这个示例将让我了解不同组件的工作原理,例如格式化 R 中的 JSON 数据等...以及作为起点。提前致谢。
最佳答案
这棵可折叠的树看起来真的很酷。我的方法是首先使用 igraph 创建一个图表。我希望已经有一个函数可以将 igraph 转换为 json,但是,它看起来像是 issue github上尚未实现。因此,这里有一个简单的函数来做到这一点。然后,您只需将结果数据插入链接的源中,您就拥有了一个可折叠的树。
## Read your data
dat <- read.table(text="ID Car Bus Train Feedback_Car Feedback_Bus Feedback_Train
23433 Yes Yes Yes Toyota GreyHound Amtrak", header=TRUE)
## Make an edgelist from your data
edges <- rbind(cbind(dat$ID, names(dat)[2:4]),
cbind(names(dat)[2:4], as.vector(t(dat[5:7]))))
## Convert to a graph data structure
library(igraph)
g <- graph_from_edgelist(edges)
## This is the non-interactive version
plot(g, layout=layout.reingold.tilford(g, root='23433'))
## Recursive function to make a list of nodes to be parsed by toJSON
## call it with 'node' as the root node (here '23433')
f <- function(g, node, size=1000) {
n <- neighbors(g, node, mode='out')
if (length(n) == 0) return( list(name=node, size=size) )
children <- lapply(n$name, function(x) f(g, x, size))
list(name=node, children=children)
}
## Convert to json
library(jsonlite)
json <- toJSON(f(g, '23433'), auto_unbox = TRUE)
## I made a directory collapsible to store the index.html from the linked
## site, as well as this data
## For completeness, you should be able to run this to see the interactive results,
## But, of course, this is creating files on your box
dir.create('collapsible')
writeLines(json, 'collapsible/data.json')
## Download the index.html
download.file("https://gist.githubusercontent.com/mbostock/4339083/raw/0d003e5ea1686dd6e79562b37f8c7afca287d9a2/index.html", "collapsible/index.html", method='curl')
## Replace with the correct data
txt <- readLines('collapsible/index.html')
txt[grepl("^d3.json", txt)] <- "d3.json('data.json', function(error, flare) {"
writeLines(txt, 'collapsible/index.html')
## Open in broweser
browseURL(paste0('file://', normalizePath('collapsible/index.html')))
结果还可以看here .
关于json - R中的可折叠树,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33141630/