Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Exclude specific object type from the global environment

Tags:

dataframe

r

I have many different objects loaded in my global environment. How can I exclude only the data frames and keep the other objects? Example:

DF1 <- data.frame(rnorm(10))
DF2 <- data.frame(rnorm(10))
DF3 <- data.frame(rnorm(10))

list1 <- list("a", "b", "c")
list2 <- list("a", "b", "c")
tf <- tempfile()
td <- tempdir()

The solution I had in mind looked something like this (of course it didn't work)

remove(pattern="*.Rdata")
like image 362
rafa.pereira Avatar asked Jan 25 '15 22:01

rafa.pereira


1 Answers

Here is a function I use for tasks like this. rmSome() does just that, removes only some of the objects from an environment. It does this by applying the function given in its first argument (i.e. an is* function like is.data.frame() for data frames, is.list() for lists, etc.) to the list of objects in the given environment and filtering out the results.

rmSome <- function(FUN, env = globalenv(), negate = FALSE) {
    fun <- match.fun(FUN)
    if(negate) fun <- Negate(fun)
    objget <- mget(ls(envir = env), envir = env)
    rmnames <- names(Filter(fun, objget))
    rm(list = rmnames, envir = env)
}

For example, you can remove all data frames from the global environment with

rmSome(is.data.frame)

So for your given example, you can remove the all the data frames like this:

## -- rm(list=ls()) here --
## Define rmSome() here 
DF1 <- data.frame(rnorm(10))
DF2 <- data.frame(rnorm(10))
DF3 <- data.frame(rnorm(10))
list1 <- list("a", "b", "c")
list2 <- list("a", "b", "c")
tf <- tempfile()
td <- tempdir()

## remove all data frames
rmSome(is.data.frame)
ls()
# [1] "list1"  "list2"  "rmSome" "td"     "tf"    

On the other hand, if you wanted to keep all the data frames and remove everything else, you would negate the removal of data frames like this:

rmSome(is.data.frame, negate = TRUE)

So far I haven't found any issues with using the other functions like is.numeric(), is.environment(), etc. for removing numerics, environments, etc. But the function is not currently set up to handle more than one object type at a time.

Update 1/28/2015: eapply() can also be used for applying a function to an environment. Here's a second function you could use if you don't like mget(). It can be used just the same as the calls above and is probably the better way to go.

rmSome2 <- function(FUN, env = globalenv(), negate = FALSE)  {
    fun <- match.fun(FUN)
    if(negate) fun <- Negate(fun)
    ue <- unlist(eapply(env, fun))
    rm(list = names(ue)[ue], envir = env)
}
like image 198
Rich Scriven Avatar answered Nov 10 '22 12:11

Rich Scriven