0

How does one create a named list of all dataframes/tibbles in the global environment in R? Is there a way to do this without manually hardcoding all dataframes/tibbles?

I.e. if the global environment contains the dataframes/tibbles df_1, my_data_1, science_1, all_data, how does one create an output that looks like:

files_list <- list(
df_1 = df_1,
my_data_1 = my_data_1,
science_1 = science_1,
all_data = all_data
)
Pontus Hedberg
  • 301
  • 1
  • 2
  • 9
  • 1
    [Use ls() or objects() to get objects of class data.frame](https://stackoverflow.com/questions/5796508/use-ls-or-objects-to-get-objects-of-class-data-frame) – Henrik Feb 12 '23 at 19:53

4 Answers4

3

We can get all objects first, then keep only the data.frames

library(purrr)

mget(ls()) %>% keep(is.data.frame)
GuedesBF
  • 8,409
  • 5
  • 19
  • 37
2

We may Filter the elements that are data.frame or tibble in the environment that we are working on - e.g. in the global env, it can be

Filter(length, eapply(.GlobalEnv, 
     function(x) if(is.data.frame(x)||is_tibble(x)) x))
akrun
  • 874,273
  • 37
  • 540
  • 662
  • Is `is_tibble` necessary here? `is.data.frame(tibble(iris))` returns TRUE anyway – GuedesBF Feb 13 '23 at 01:33
  • @GuedesBF Not really, it is just to make it explicit. If I have just used `is.data.frame` (which would be the base class), then there would be comments that it is not clear how it includes the tibble case. – akrun Feb 13 '23 at 06:47
1

A base way, combining methods of @GuedesBF and @akrun could be using ls, mget and Filter.

Filter(is.data.frame, mget(ls()))
#Filter(is.data.frame, mget(ls(.GlobalEnv))) #More explicit using globEnv
GKi
  • 37,245
  • 2
  • 26
  • 48
0

Please try the below code which will generate a df

naml <- list()

  for (i in seq_along(ls(envir =.GlobalEnv))) {
    j <- ls(envir =.GlobalEnv)[i]
  if (any(class(get(j))=='data.frame')) name <- {j} else name <- NA
  if (any(class(get(j))=='data.frame')) class <- class(get(j))[3] else class <- NA
  if (!is.na(name) & !is.na(class)) {
  df <- data.frame(namex=name,classx=class)
  naml[[j]] <- df
  }
  }

df2 <- do.call(rbind, naml) %>% rownames_to_column('name') %>% 
pivot_wider(names_from = name, values_from = namex)

jkatam
  • 2,691
  • 1
  • 4
  • 12