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

Converting the names of a list elements as a variable in a data.frame

I have a named List of data.frames. I was wondering how to convert the name ("bar1",…,"bar4") of each element List as a column next to each data.frame?

My final desired_output is shown below.

List <- list(bar1=data.frame(study="A",sd = 1), bar2=data.frame(study=c("B","C"),sd=2:3),
     bar3=data.frame(study="Z",sd = 4), bar4=data.frame(study="H",sd=5))

# desired_output:
"
  study sd   id
      A  1 bar1
      B  2 bar2
      C  3 bar2
      Z  4 bar3
      H  5 bar4
"

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

>Solution :

Here’s a tidyverse solution using map2() from the purrr library. First, I grabbed the names of the list elements and stored them in a vector, n:

n <- names(List)

Then we can iterate over List and n at the same time, calling cbind() to add a variable (i.e., column) to each data frame:

map2(List, n, ~ cbind(.x, Name = .y))

Output:


$bar1
study sd Name
1 A 1 bar1

$bar2
study sd Name
1 B 2 bar2
2 C 3 bar2

$bar3
study sd Name
1 Z 4 bar3

$bar4
study sd Name
1 H 5 bar4

We can collapse List to a single data frame with a call to bind_rows():

result <- map2(List, n, ~ cbind(.x, Name = .y))
bind_rows(result)

Output:


study sd Name
1 A 1 bar1
2 B 2 bar2
3 C 3 bar2
4 Z 4 bar3
5 H 5 bar4

In one statement:

map2(List, names(List), ~ cbind(.x, Name = .y)) %>% 
  bind_rows()
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