Это разборное дерево выглядит действительно круто. Мой подход заключается в том, чтобы сначала создать граф, используя 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.
Что такое набор данных, упомянутый выше, это csv? – Cyril
@ Кирилл, да, это правильно –
Взгляните на [этот пример] (http://104.131.111.111:3838/ggtree/) Тяжелый подъем сделан D3.js, но он в блестящем приложении. – jeremycg