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?
ls() function in R Language is used to list the names of all the objects that are present in the working directory.
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.
The ls() code lists all of the objects in your workspace.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With