r - 使 .id 参数在绑定(bind)嵌套列表/R 后显示对象的名称

标签 r dplyr purrr nested-lists

我正在处理一个大的嵌套列表。上一篇文章已经帮助了我,但我陷入了从大型嵌套列表中形成可用数据框的最后一步。 在此数据框中应该有一个“id”列,显示列表中 tibble 的名称。我尝试了 bind.rows(.id='id') 但它丢弃了名称并为其提供了数字索引。我怎样才能避免这种情况? 这是我的问题的最小化版本: (我不太确定这个例子是否足够精确,因为我无法命名每个列表元素,但我希望这个想法能够被理解)

a<-tibble (a=numeric(7),
           b=letters[7:1],
           c=integer(length=1))

b<-tibble (a=integer(length=1),
           b=as.numeric(8),
           c=letters[7:1])


c<- tibble(.rows = 2)

A<-list(list(a,b,c))
B<-list(A,list(a,b,c)) 
C<-list(A,B)

riddle<-list(A,B,C)

以下是我运行的代码,用于获取原始数据的格式,但您会看到 id 列仅获取数字索引,例如,对于我的原始数据

rrapply(riddle, condition = function(x) all(dim(x)>0),  
        f =  function(x) 
        {
          # change to unique column names
          names(x) <- make.unique(names(x))
          x %>%  
            # convert all columns to character if there
            # are mismatch in column types in any list elements
            mutate(across(everything(), as.character))
        },      classes = "data.frame", how= "flatten") %>% 
  # bind the flattened list of data.frame/tibbles to single dataset
  bind_rows(.id="id") %>%
  # do the column type conversion 
  type.convert(as.is = TRUE) 

假设我的示例具有 id 的 12 个值的名称 - 我需要如何以及执行哪个命令来获取对象的名称作为 .id 列的值?

最佳答案

如果列表有名称,那么我们也许能够使用列表的名称提取并创建“id”

library(rrapply)
library(dplyr)
library(stringr)
A <-list(list(a,b,c))
B <- list(A = A, list(a, b, c))
C <- list(A=A, B = B)
riddle <- list(A = A, B = B, C = C)

-测试

out <- rrapply(riddle, condition = function(x) all(dim(x)>0),  
        f =  function(x, .xparents) 
        {
          # change to unique column names
          names(x) <- make.unique(names(x))
          x %>%  
        mutate(id =  str_c(setdiff(.xparents, ""), 
             collapse = "_"), .before = 1 ) %>%
            # convert all columns to character if there
            # are mismatch in column types in any list elements
            mutate(across(everything(), as.character)) 
        },      classes = "data.frame", how= "flatten") %>%
    bind_rows() %>% 
    type.convert(as.is = TRUE) 

-输出

> out
# A tibble: 84 × 4
   id        a b     c    
   <chr> <int> <chr> <chr>
 1 A_1       0 g     0    
 2 A_1       0 f     0    
 3 A_1       0 e     0    
 4 A_1       0 d     0    
 5 A_1       0 c     0    
 6 A_1       0 b     0    
 7 A_1       0 a     0    
 8 A_1_2     0 8     g    
 9 A_1_2     0 8     f    
10 A_1_2     0 8     e    
# … with 74 more rows

关于r - 使 .id 参数在绑定(bind)嵌套列表/R 后显示对象的名称,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/74978028/

相关文章:

R - 将列值嵌套到单个向量列(类型列表)中

r - 检查字符串中的字符是否为大写

r - 为什么 model.matrix 这么慢?

R,在向量化的范围内加入

r - 使用 dplyr 动态创建列

r - 强制 imap 使用命名向量上的索引

r - 等同于min()的rowMeans()

r - 在 levelplot 中指定 NA 栅格值的颜色(R 包 rasterVis)

r - 如何在 mutate_at 中取消引用拼接?

r - 使用 purrr 映射按列对迭代汇总