[ACCEPTED]-Transform a dataframe into a tree structure list of lists-networkd3
Accepted answer
Here is a recursive definition:
maketreelist <- function(df, root = df[1, 1]) {
if(is.factor(root)) root <- as.character(root)
r <- list(name = root)
children = df[df[, 1] == root, 2]
if(is.factor(children)) children <- as.character(children)
if(length(children) > 0) {
r$children <- lapply(children, maketreelist, df = df)
}
r
}
canadalist <- maketreelist(df)
That produces 9 what you desire. This function assumes that 8 the first column of the data.frame
(or matrix
) you pass 7 in contains the parent
column and the second column 6 has the child
. it also takes a root
parameter which 5 allows you to specify a starting points. It 4 will default to the first parent in the 3 list.
But if you really are interested in 2 playing round with trees. The igraph
package might 1 be of interest
library(igraph)
g <- graph.data.frame(df)
plot(g)
Source:
stackoverflow.com
More Related questions
Cookie Warning
We use cookies to improve the performance of the site. By staying on our site, you agree to the terms of use of cookies.