简体   繁体   中英

Mutate in list of lists of dataframes

I have the following 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")

I want to add a column (ideally using tidyverse) in every dataframe with the top level name of the list. I have tried various ways using map and modify_depth without much success as I don't understand how I could access list element names at higher levels ]when I map at the level of the dataframe.

Please see below how I would like my_list to change:

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

Here is one way to do it with imap + modify_depth . imap allows you to access the name of the list element as the second argument:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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