简体   繁体   中英

how can I create a list combining elements from tibble?

I have the following tibble:

  ID    group   val_1   val_2
  <chr> <chr>   <dbl>  <dbl>
1 A     RED          1     3
2 A     BLUE         2     4
3 A     BLACK        1     5
4 B     RED          2     5
5 B     BLUE         1     6
6 B     BLACK        2     6

And I want to go through this tibble to create a list of lists.Each nested list should be a list for each ID with the following elements. For example for ID==A:

A
$BLACK
[1] 1 5

$RED
[1] 1 3

$BLUE
[1] 2 4

The second element of the list should be the list for ID==B. I already tried purrr::transpose() but it does not do exactly what I want as it creates a list of 6 elements (one per row). I tried group_by(ID) but it did not generate the expected output. I would appreciate any suggestions.

One option would be split

lapply(split(df1, df1$ID), function(x) lapply(split(x[3:4],
         x$group), unlist, use.names = FALSE))
#$A
#$A$BLACK
#[1] 1 5

#$A$BLUE
#[1] 2 4

#$A$RED
#[1] 1 3


#$B
#$B$BLACK
#[1] 2 6

#$B$BLUE
#[1] 1 6

#$B$RED
#[1] 2 5

With tidyverse , we can also nest

library(dplyr)
df1 %>% 
   group_by(ID, group) %>% 
   nest

Or another option is to convert to 'long' format with pivot_longer and then do the split

library(tidyr)
library(purrr)
df1 %>% 
  pivot_longer(cols = -c(ID, group)) %>%
  split(.$ID) %>% 
  map(~  {split(.x$value, .x$group)})

data

df1 <- structure(list(ID = c("A", "A", "A", "B", "B", "B"), group = c("RED", 
"BLUE", "BLACK", "RED", "BLUE", "BLACK"), val_1 = c(1L, 2L, 1L, 
2L, 1L, 2L), val_2. = c(3L, 4L, 5L, 5L, 6L, 6L)), 
 class = "data.frame", row.names = c("1", 
"2", "3", "4", "5", "6"))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM