Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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!

>Solution :

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))
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading