In below example, I'm creating a nested representation of a tree. I'm expecting that children "1,a" and "1,b" to be associated with parent "1". Yet it ends up to be associated with parent "2", while it shouldn't. Do you have any ideas of what is going wrong?
library(data.tree)
data <- data.frame(
Name = c("A", "A1", "A2", "A1a", "A1b", "A2a", "A2b", "A2c","B"),
Path = c("1", "1,a", "1,b", "1,a,1", "1,a,2", "1,b,1", "1,b,2", "1,b,3","2")
)
my_tree <- data %>%
rowwise() %>%
mutate(pathString = strsplit(Path, ',') %>% unlist() %>% paste(collapse = '/')) %>%
as.Node()
treeToList <- function(node) {
list(
text = node$Name,
li_attr = list(id = node$Path),
state = list(opened = TRUE),
children = Map(
node$children,
f = treeToList
)
)
}
treeToList(my_tree)
It seems you provided a forest rather than a tree, a tree has one root. Therefore your 1 and 2 should have a common root, and this should be explicit
# the diagram you started with
levelName
1 1
2 ¦--a
3 ¦ ¦--1
4 ¦ °--2
5 °--b
6 ¦--1
7 ¦--2
8 °--3
new code
my_tree <- data |>
rowwise() |>
mutate(Path=paste0("treeroot,",Path)) |> # ! The Change ! #
mutate(pathString = strsplit(Path, ',') |> unlist() |> paste(collapse = '/')) |>
as.Node()
my_tree
levelName
1 treeroot
2 ¦--1
3 ¦ ¦--a
4 ¦ ¦ ¦--1
5 ¦ ¦ °--2
6 ¦ °--b
7 ¦ ¦--1
8 ¦ ¦--2
9 ¦ °--3
10 °--2
we succesfully have both 1 and 2 under the common treeroot