0

I have created several data frames and I need to select some of them based on their name, for example only those with "ssp126" or "2011-2040", in this list below, and then combine them into single data frame.

> names(which(unlist(eapply(.GlobalEnv,is.data.frame))))
 [1] "map_2071-2100_ssp370" "map_2041-2070_ssp585" "map_2011-2040_ssp585" "map_2041-2070_ssp370"
 [9] "map_2011-2040_ssp126" "map_2041-2070_ssp126" "map_2071-2100_ssp126"
[13] "map_2011-2040_ssp370" "map_1951-1980"        "map_2071-2100_ssp585"               
[17] "map_1981-2010"  

Someone have a suggestion? Thanks!

Tribaldi
  • 177
  • 9
  • 4
    `mget(grep('ssp126|2011-2040', names(which(unlist(eapply(.GlobalEnv,is.data.frame)))), value = TRUE))` – Allan Cameron Feb 20 '23 at 15:01
  • 1
    And of course, if you instead [created your dataframes in a (named) list from the get-go](https://stackoverflow.com/a/24376207/17303805), it would just be `df_list[grepl("ssp126|2011-2040", names(df_list))]`. – zephryl Feb 20 '23 at 15:14

1 Answers1

1

Solution: use the function mget and grep to list all my data frames, in my Global environment, with "ssp126" or "2011-2040" (for ex) in their names.

Then, use the function data.table::rbindlist(), according to How do I make a list of data frames? answer, to combine my list of data frames, chosen by names, into a single data frame, such as

my_df <- mget(grep('ssp126|2011-2040', 
                       names(which(unlist(eapply(.GlobalEnv,is.data.frame)))), 
                       value = TRUE)) %>% 
  data.table::rbindlist(.)
Tribaldi
  • 177
  • 9