这个可折叠的树看起来非常酷。我的方法是首先使用igraph
创建一个图形。我希望已经有一个将igraph转换为json的函数,但看起来这是github上尚未实现的问题。因此,这里有一个简单的函数来实现这个功能。然后,您只需要将结果数据插入到链接源中,就可以得到一个可折叠的树。
dat <- read.table(text="ID Car Bus Train Feedback_Car Feedback_Bus Feedback_Train
23433 Yes Yes Yes Toyota GreyHound Amtrak", header=TRUE)
edges <- rbind(cbind(dat$ID, names(dat)[2:4]),
cbind(names(dat)[2:4], as.vector(t(dat[5:7]))))
library(igraph)
g <- graph_from_edgelist(edges)
plot(g, layout=layout.reingold.tilford(g, root='23433'))
![enter image description here](https://istack.dev59.com/aN3DU.webp)
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)
}
library(jsonlite)
json <- toJSON(f(g, '23433'), auto_unbox = TRUE)
dir.create('collapsible')
writeLines(json, 'collapsible/data.json')
download.file("https://gist.githubusercontent.com/mbostock/4339083/raw/0d003e5ea1686dd6e79562b37f8c7afca287d9a2/index.html", "collapsible/index.html", method='curl')
txt <- readLines('collapsible/index.html')
txt[grepl("^d3.json", txt)] <- "d3.json('data.json', function(error, flare) {"
writeLines(txt, 'collapsible/index.html')
browseURL(paste0('file://', normalizePath('collapsible/index.html')))
这些结果也可以在这里查看。