I am new to R, and need to create hierarchical data format in a shiny application, and hence cannot code it manually. Suppose I have a data frame
parents labels values
1 Everything 10
2 earth land 30
3 earth ocean 30
4 mars valley 40
5 mars crater 40
6 land forest 10
7 land river 10
8 ocean kelp 20
9 ocean fish 20
10 fish shark 10
11 fish tuna 10
12 Everything venus 40
13 Everything earth 20
14 Everything mars 30
created manually:
df <- data.frame(parents = c("","earth", "earth", "mars", "mars", "land", "land", "ocean", "ocean", "fish", "fish", "Everything", "Everything", "Everything"),
labels = c("Everything", "land", "ocean", "valley", "crater", "forest", "river", "kelp", "fish", "shark", "tuna", "venus","earth", "mars"),
values = c(10, 30, 30, 40, 40, 10, 10, 20, 20, 10, 10, 40, 20, 30)
)
The programatically created tibble nested list should look like this:
df
# A tibble: 3 x 3
name value children
<chr> <dbl> <list>
1 earth 30 <tibble [2 × 3]>
2 mars 40 <tibble [2 × 2]>
3 venus 30 <NULL>
I can create it manually like this:
library(dplyr)
df <- tibble(
name = c("earth", "mars", "venus"), value = c(30, 40, 30),
children = list(
tibble(name = c("land", "ocean"), value = c(10,20), # 2nd level
children = list(
tibble(name = c("forest", "river"), value = c(3,7)), # 3rd level
tibble(name = c("fish", "kelp"), value = c(10,5),
children = list(
tibble(name = c("shark", "tuna"), value = c(2,6)), # 4th level
NULL # kelp
))
)),
tibble(name = c("crater", "valley"), value = c(20,20)),
NULL # venus
)
)
Manual conversion is not useful to me. Note that I am getting rid of the top layer of 'Everything' , which is fine with me. Can someone help me convert it to nested tibble list programmatically?
Thanks very much!!