Home > Mobile >  Create Nested List from Tibble
Create Nested List from Tibble

Time:12-07

I'd like to create a nested listed from a tibble, so the data is stored more efficiently and it is easier to extract information with subsetting.

I have a 3 column tibble like the following:

library(dplyr)

df <- tribble(
~a,~b,~c,
"a1", "b1", 1,
"a1", "b1", 2,
"a1", "b2", 1, 
"a1", "b2", 2,
)

I'd like to convert this to a list identical to this:

list(a1 = list(b1 = 1:2, b2 = 1:2))

Does anyone know how I can do this please?

Thanks

CodePudding user response:

Split twice, i.e.

lapply(split(df,df$a), function(x) split(x$c,x$b))

$a1
$a1$b1
[1] 1 2

$a1$b2
[1] 1 2

CodePudding user response:

Something like the following?

library(tidyverse)

df <- tribble(
  ~a,~b,~c,
  "a1", "b1", 1,
  "a1", "b1", 2,
  "a1", "b2", 1, 
  "a1", "b2", 2,
)

df %>%
  group_by(a,b) %>% group_split() %>% map(~ list(.x$c) %>% set_names(.x$b[1])) %>% 
  unlist(recursive = F) %>% list %>% set_names(unique(df$a))

#> $a1
#> $a1$b1
#> [1] 1 2
#> 
#> $a1$b2
#> [1] 1 2
  • Related