Use ls() or objects() to get objects of class data.frame

You can get an object from its name with get or mget and iterate with one of the apply type functions. For example,

sapply(mget(ls(), .GlobalEnv), is.data.frame)

will tell you which items in the global environment are data frames. To use within a function, you can specify an environment to the ls call.


The answer given by @jverzani about figuring out which objects are data frames is good. So let's start with that. But we want to select only the items that are data.frames. So we could do that this way:

#test data
df <- data.frame(a=1:10, b=11:20)
df2 <- data.frame(a=2:4, b=4:6)
notDf <- 1

dfs <- ls()[sapply(mget(ls(), .GlobalEnv), is.data.frame)]

the names of the data frames are now strings in the dfs object so you can pass them to other functions like so:

sapply( dfs, function(x)  str( get( x ) ) )

I used the get() command to actually get the object by name (see the R FAQ for more about that)

I've answered your qeustion above, but I have a suspicion that if you would organize your data frames into list items your code would be MUCH more readable and easy to maintain. Obviously I can't say this with certainty, but I can't come up with a use case where iterating through all objects looking for the data frames is superior to keeping your data frames in a list and then calling each item in that list.

Tags:

R