Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I get subsets for multiple data frames at same time?

Tags:

r

I have 100 data sets about data for 100 different locations.

I want to get the subset of the same variables for each data set. Something like:

dataset1<-subset(dataset1, which(gender=='F'))
dataset2<-subset(dataset2, which(gender=='F'))
dataset3<-subset(dataset3, which(gender=='F'))
dataset4<-subset(dataset4, which(gender=='F'))

.....

How can I get all 100 data sets done at the same time instead of writing 100 lines?

like image 688
Bing Avatar asked Mar 03 '23 21:03

Bing


2 Answers

You can put the dataset in a list and then use subset on each using lapply

list_df <- lapply(mget(paste0('dataset', 1:100)),function(x) subset(x, gender=='F'))

It is better to keep data in a list but if needed as separate dataframes, we can use list2env

list2env(list_df,.GlobalEnv)
like image 59
Ronak Shah Avatar answered Mar 05 '23 09:03

Ronak Shah


We can use map from purrr

library(dplyr)
library(purrr)
library(stringr)
list_df  <- mget(str_c("dataset", 1:100)) %>%
                   map(~ .x %>%
                               filter(gender == "F"))
list2env(list_df, .GlobalEnv)
like image 33
akrun Avatar answered Mar 05 '23 09:03

akrun