簡體   English   中英

在數據框列表列表中進行變異

[英]Mutate in list of lists of dataframes

我有以下數據框列表列表。

 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")

這是使用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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM