简体   繁体   English

如何创建一个组合来自 tibble 的元素的列表?

[英]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.而我想通过这个tibble来go创建一个列表列表Each nested list should be a list for each ID with the following elements.每个嵌套列表应该是具有以下元素的每个 ID 的列表。 For example for ID==A:例如对于 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.列表的第二个元素应该是 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).我已经尝试过purrr::transpose()但它并没有完全满足我的要求,因为它创建了一个包含 6 个元素的列表(每行一个)。 I tried group_by(ID) but it did not generate the expected output.我尝试了group_by(ID) ,但它没有生成预期的 output。 I would appreciate any suggestions.我将不胜感激任何建议。

One option would be split一种选择是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使用tidyverse ,我们也可以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或者另一种选择是使用pivot_longer转换为“long”格式,然后进行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"))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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