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