Getting names of objects in an R workspace by type

To identify data frames in a workspace, and iterate over them by name, use Filter() with a few other functions:

> foo <- data.frame(matrix(1:10,ncol=2))
> rainbow <- c("red","orange","yellow","green","blue","indigo","violet")
> hello <- function(x) cat("Hello, ",x,"!\n",sep="")
> dfNames <- names(Filter(function(x) x=="data.frame",
+ sapply(objects(),function(x) class(get(x)))))
> dfNames
[1] "foo"
>

Here, objects() lists objects in the workspace, class() identifies their classes, and sapply() looks at each object in turn, returning a character vector to pass to Filter(). Importantly, get() must be used in class(), otherwise only the names of the objects are evaluated, and class() will always return “character”.

Each data frame can then be called by name in a loop:

> for( i in seq(along=dfNames) ) {
+ curr.df <- get(dfNames[i])
+ ## do things with the df
+ }

Note: not done here, but storing names in a list will allow for use of the “apply” family of functions, avoiding the need for a loop.

Advertisements
This entry was posted in data munging, R and tagged . Bookmark the permalink.