AdeelK93 / collapsibleTree

Create Interactive Collapsible Tree Diagrams in R using D3.js
https://adeelk93.github.io/collapsibleTree/
158 stars 41 forks source link

Function to convert between hierarchical data and parent-child data #29

Closed jl5000 closed 6 years ago

jl5000 commented 6 years ago

I'm in the position where I have a hierarchical dataframe, but I want to take advantage of the greater functionality of a parent-child format. Is it possible to implement a function to do this conversion?

AdeelK93 commented 6 years ago

How about something like this?

hierarchalToNetworkDf <- function(df, hierarchy, root = deparse(substitute(df))) {
  # the hierarchy that will be used to create the tree
  df$pathString <- paste(
    root,
    apply(df[,hierarchy], 1, paste, collapse = "//"),
    sep="//"
  )
  # convert the data frame into a data.tree node
  node <- data.tree::as.Node(df, pathDelimiter = "//")
  # convert the data.tree node back into a data frame
  data.tree::ToDataFrameNetwork(node)
}
jl5000 commented 6 years ago

Unfortunately the code didn't give me the output required...however, I am finishing off a function to hopefully do this conversion.

AdeelK93 commented 6 years ago

Feel free to share it when you have it figured out!

jl5000 commented 6 years ago

Hello,

So the majority of credit goes to the user Prem at StackOverflow for this solution, I've just added some bits to turn it into a function:

convert_hierarchy <- function(df) {

  data.table::rbindlist(lapply(as.data.frame(zoo::rollapply(names(df), ncol(df) - 1, c), 
                                             stringsAsFactors = F), 
                               function(x) select(df, c(x)))) %>%
                               distinct() %>%
                               set_names(c("parent", "child")) %>%
                               filter(!is.na(child), !is.na(parent)) %>%
                               rbind(data.frame(parent = NA,  child = df[[1,1]]), .)

}

Note that this function: