Reputation: 11
I have columns arranged like the below:
Product: Charge:
P1 C1
P1 C2
P2 C1
P2 C3
P3 C2
I need to show a tree diagram that sets the first product, P1 and then shows all the charges attached to that (p1 - c1 and p1 to c2) and then the next quadrant shows the products that are attached to those charges c1 and c2. Then the next quadrant shows the charges attached to those products and so on and so on until there are no more relations to add.
FromDataFrameNetwork does not work as it says cannot find root name. Network is not a tree. Please help.
See above explanation.
Upvotes: 1
Views: 57
Reputation: 101064
You can use igraph
like below
library(igraph)
g <- graph_from_data_frame(df, directed = FALSE)
dfout <- setNames(
do.call(
rbind,
lapply(
all_shortest_paths(g,
from = "P1",
to = V(g)[degree(g) == 1]
)$vpath,
\(x) {
as.data.frame(embed(names(x), 2)[, 2:1])
}
)
),
c("from", "to")
)
and you will obtain
> dfout
from to
1 P1 C2
2 C2 P3
3 P1 C1
4 C1 P2
5 P2 C3
and its visualization
dfout %>%
graph_from_data_frame() %>%
plot(layout = layout_as_tree)
If you want tree diagram
> library(data.tree)
> FromDataFrameNetwork(dfout)
levelName
1 P1
2 ¦--C2
3 ¦ °--P3
4 °--C1
5 °--P2
6 °--C3
Upvotes: 1