[英]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.