Closed jl5000 closed 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)
}
Unfortunately the code didn't give me the output required...however, I am finishing off a function to hopefully do this conversion.
Feel free to share it when you have it figured out!
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:
tidyverse
, data.table
, and zoo
packages.
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?