Reputation: 1285
I have a list of dataframes
mydata1<-data.frame(ID=1:3,age=c(15,20,32),sex=c("M","F","M"))
mydata2<-data.frame(ID=11:14,age=c(35,22,14,45),sex=c("F","F","M","M"),Diagnosis=c("Pneumony","AIDS","Cancer","Asthma"))
mydata3<-data.frame(ID=21:22,age=c(24,22),sex=c("M","F"),Country=c("France","UK"))
LST<-list(mydata1=mydata1,mydata2=mydata2,mydata3=mydata3)
and I want to select certain columns (ID and ages in this case) from each of the dataframe and then stack them by rowbind()
in order to have such a dataset. I want to do all the manipulations on the list directly.
ID age
1 1 15
2 2 20
3 3 32
4 11 35
5 12 22
6 13 14
7 14 45
8 21 24
9 22 22
Upvotes: 0
Views: 105
Reputation: 389265
Here is a base R option -
cols <- c('ID', 'age')
do.call(rbind, lapply(LST, `[`, cols))
Upvotes: 2
Reputation: 41260
You could use map_dfr
from purrr
:
library(dplyr)
library(purrr)
LST %>% map_dfr(~.x %>% select(ID,age))
ID age
1 1 15
2 2 20
3 3 32
4 11 35
5 12 22
6 13 14
7 14 45
8 21 24
9 22 22
map_dfr
directly binds rows for outputs of type data.frame
.
The ~.x %>% select(ID,age)
notation is a shorthand for function(df) df %>% select(ID,age)
Upvotes: 2