【问题标题】:Mutate in list of lists of dataframes在数据框列表中变异
【发布时间】:2018-03-06 00:42:25
【问题描述】:

我有以下数据框列表。

 my_list <- list(
   list(a = data.frame(a1 = c(1,2), b1 = c(3,4), c1 =c(5,6)),
        b = data.frame(b1 = c(1,2))),
   list(a = data.frame(a1 = c(11,21), b1 = c(31,41), c1 =c(51,61)),
        b = data.frame(b1 = c(12,22))))
 names(my_list) = c("one", "two")

我想在每个数据框中使用列表的顶级名称添加一列(最好使用 tidyverse)。我尝试了使用 map 和 modify_depth 的各种方法,但没有取得多大成功,因为当我在数据帧级别进行映射时,我不明白如何在更高级别访问列表元素名称。

请看下面我希望 my_list 如何更改:

 my_desired_list <- list(
   list(a = data.frame(a1 = c(1,2), b1 = c(3,4), c1 =c(5,6), col = "one"),
        b = data.frame(b1 = c(1,2), col = "one")),
   list(a = data.frame(a1 = c(11,21), b1 = c(31,41), c1 =c(51,61), col = "two"),
        b = data.frame(b1 = c(12,22), col = "two")))
 names(my_desired_list) = c("one", "two")

【问题讨论】:

    标签: r dataframe tidyverse purrr dplyr


    【解决方案1】:

    这是使用imap + modify_depth 的一种方法。 imap 允许您访问列表元素的名称作为第二个参数:

    library(tidyverse)
    my_list %>% imap(~ modify_depth(.x, 1, mutate, col=.y))
    # in imap the first argument .x stand for the elements of my_list, the second argument
    # stands for the name for this corresponding element
    
    #$one
    #$one$a
    #  a1 b1 c1 col
    #1  1  3  5 one
    #2  2  4  6 one
    
    #$one$b
    #  b1 col
    #1  1 one
    #2  2 one
    
    
    #$two
    #$two$a
    #  a1 b1 c1 col
    #1 11 31 51 two
    #2 21 41 61 two
    
    #$two$b
    #  b1 col
    #1 12 two
    #2 22 two
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-01-07
      • 2021-10-10
      相关资源
      最近更新 更多