Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

r

Is there anyway I can loop through some set of objects and apply a function to each?

When I type ls() or objects(), it returns a list of object names. I could like to iterate through this list, identify those which are data.frame, and then run a function against each object.

How do I pass an entry from ls or objects through a function?

like image 224
Ray Avatar asked Apr 26 '11 21:04

Ray


People also ask

What does ls () do in R?

ls() function in R Language is used to list the names of all the objects that are present in the working directory.

Is a data frame an object in R?

A data. frame object in R has similar dimensional properties to a matrix but it may contain categorical data, as well as numeric. The standard is to put data for one sample across a row and covariates as columns. On one level, as the notation will reflect, a data frame is a list.

Which of the following function list all the objects in the workspace?

The ls() code lists all of the objects in your workspace.


2 Answers

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.

like image 110
JD Long Avatar answered Sep 21 '22 17:09

JD Long


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.

like image 26
jverzani Avatar answered Sep 20 '22 17:09

jverzani