2

Is there a way to list objects based on their classes ? For example, list only the dataframe objects in the workspace.

Veera
  • 861
  • 1
  • 9
  • 18
  • 1
    Check [this post](http://stackoverflow.com/questions/35371882/how-can-i-access-all-objects-of-class-data-frame-inside-globalenv-in-r) – talat Jul 15 '16 at 12:49
  • @docendodiscimus Thanks for the link. I liked the `dflist <- Filter(is.data.frame, as.list(.GlobalEnv))` solution . – Veera Jul 15 '16 at 12:58

2 Answers2

4

Here is a way with sapply and class to retrieve the names of the objects in the environment that are data.frames:

ls()[sapply(ls(), function(i) class(get(i))) == "data.frame"]
lmo
  • 37,904
  • 9
  • 56
  • 69
  • Why are you complicating this? Use this `ls()[sapply(ls(),function(t) is.data.frame(get(t)))]` – user2100721 Jul 15 '16 at 12:54
  • That would return something different than what I said. That would be a logical vector. I am returning the names of the objects. I'm not sure that your statement is that much cleaner than mine. – lmo Jul 15 '16 at 12:57
  • 1
    The exact code is already there in the dupe post which was dupe tagged 4 mins before this was posted. – akrun Jul 15 '16 at 12:57
  • @user2100721 Sorry for the confusion. It was the other way around. Thanks for asking. To be clear, `ls()[sapply(ls(), function(i) class(get(i))) == "data.frame"]` didn't list the data table objects (which are dataframes too) but `ls()[sapply(ls(),function(t) is.data.frame(get(t)))]` listed all dataframes. – Veera Jul 15 '16 at 13:17
0
for (obj in ls()) { 
    if(class(get(obj)) == "data.frame")
       print(obj)
}
Ronak Shah
  • 377,200
  • 20
  • 156
  • 213