Home > database >  How to create a new column in all components of a list based on the name of each component?
How to create a new column in all components of a list based on the name of each component?

Time:04-26

Here is an example list:

list1 <- list(a = structure(list(a = c(1, 2, 4, 5), b = c(1, 1, 1, 1), 
    d = c(2, 2, 2, 2)), class = "data.frame", row.names = c(NA, 
-4L)), b = structure(list(a = c(1, 2, 4, 5), b = c(1, 1, 1, 1
), d = c(2, 2, 2, 2)), class = "data.frame", row.names = c(NA, 
-4L)), d = structure(list(a = c(1, 2, 4, 5), b = c(1, 1, 1, 1
), d = c(2, 2, 2, 2)), class = "data.frame", row.names = c(NA, 
-4L)))

I would like to add a column inside each component of the list (i.e. a, b, d) such that the fourth column indicates the name of component. Here's an example of what I'm looking for.

list2 <- list(a = structure(list(a = c(1, 2, 4, 5), b = c(1, 1, 1, 1), 
    d = c(2, 2, 2, 2), name = structure(c(1L, 1L, 1L, 1L), class = "factor", .Label = "a")), class = "data.frame", row.names = c(NA, 
-4L)), b = structure(list(a = c(1, 2, 4, 5), b = c(1, 1, 1, 1
), d = c(2, 2, 2, 2), name = structure(c(1L, 1L, 1L, 1L), class = "factor", .Label = "b")), class = "data.frame", row.names = c(NA, 
-4L)), d = structure(list(a = c(1, 2, 4, 5), b = c(1, 1, 1, 1
), d = c(2, 2, 2, 2), name = structure(c(1L, 1L, 1L, 1L), class = "factor", .Label = "c")), class = "data.frame", row.names = c(NA, 
-4L)))

I have tried variants of

list2 <- lapply(list1, function(x) cbind(list1, name = names(x[1])))

but to no avail. I understand why the above wouldn't work, but couldn't figure out a different solution. Thanks for the help!

CodePudding user response:

We can use imap

library(purrr)
library(dplyr)
imap(list1, ~ .x %>%
           mutate(name = .y))

Or in base R with Map

Map(cbind, list1, name = names(list1))

-output

$a
  a b d name
1 1 1 2    a
2 2 1 2    a
3 4 1 2    a
4 5 1 2    a

$b
  a b d name
1 1 1 2    b
2 2 1 2    b
3 4 1 2    b
4 5 1 2    b

$d
  a b d name
1 1 1 2    d
2 2 1 2    d
3 4 1 2    d
4 5 1 2    d

With lapply, it can be done by looping over the sequence or names

lapply(names(list1), function(x) cbind(list1[[x]], name = x))
  • Related