0

I would like to get the list of loaded dataframes (i.e., the names of the data frames) in an R session.

I wrote the following code but it only puts the last found data.frame in variable y and does not even print it out:

for(y in ls()){
  if(is.data.frame(y) == TRUE){
    print(y) }
}

If I use the following code, all data and values are printed:

for(z in ls()){
  print(z)
}

My questions:

  • How do I get to print only dataframes?
  • Crucially, how do I put the result in a useable variable?

System used:

  • R version: 4.1.1 (2021-08-10)
  • RStudio version: 1.4.1717
  • OS: macOS Catalina version 10.15.7
pdeli
  • 436
  • 3
  • 13
  • Possible duplicate of [Get list of available data frames](https://stackoverflow.com/q/19684819/903061) - it's a little different because that user wants the names, and you want the objects. – Gregor Thomas Sep 15 '21 at 15:51
  • But an idea from there, `mget(names(which(unlist(eapply(.GlobalEnv,is.data.frame)))))`. This would be a little slower potentially if you have a lot of large non-dataframe objects, but a shorter to write version would be `Filter(is.data.frame, mget(ls()))` – Gregor Thomas Sep 15 '21 at 15:53
  • http://stackoverflow.com/questions/1358003/tricks-to-manage-the-available-memory-in-an-r-session for the `.ls.objects` function. Once you have that, you can use `rownames(subset(.ls.objects(n=Inf), Type %in% c("data.frame", "data.table", "tbl_df")))`. – r2evans Sep 15 '21 at 16:13
  • @GregorThomas: thank you for your answers and sorry if my question is a duplicate. It makes days I'm looking as how to solve this issue of mine, but did not find anything with the keywords I used. Also, what both solutions you gave do are loading the existing data frames into one, giant, data frame. What I would like is just a list of the names of the loaded data frames. – pdeli Sep 16 '21 at 14:46
  • There's nothing wrong with asking a duplicate question - now this question will serve as a pointer to the duplicate, making it easier to find. With your clarification, this is actually an exact duplicate. The `mget()` I added to the other question's answers is what gets the objects and puts them in a list. If you only want the names, leave off the `mget` and `names(which(unlist(eapply(.GlobalEnv,is.data.frame))))` should get you what you want. – Gregor Thomas Sep 16 '21 at 14:58
  • @GregorThomas: it works like a charm! Thank you!!! – pdeli Sep 16 '21 at 15:11
  • @r2evans: it works very well, with loads of extra information. Thank you very much. – pdeli Sep 16 '21 at 15:11

0 Answers0