[ACCEPTED]-Transform a dataframe into a tree structure list of lists-networkd3

Accepted answer
Score: 12

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)

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

g <- graph.data.frame(df)

canada tree in igraph

More Related questions