Here is the function that I use for such tasks. rmSome() does just that, only removes some objects from the environment. It does this by applying the function specified in its first argument (i.e. the is* function, such as is.data.frame() for data frames, is.list() for lists, etc.) a list of objects in a given environment and filtering 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 delete all data frames from the global environment using
rmSome(is.data.frame)
So, for this example, you can delete all data frames as follows:
#
On the other hand, if you want to save all data frames and delete everything else, you can negate the deletion of data frames as follows:
rmSome(is.data.frame, negate = TRUE)
So far, I have not found any problems using other functions like is.numeric() , is.environment() , etc. to remove numerical values, environments, etc. But the function is not currently configured to handle multiple type objects at a time.
Update 1/28/2015: eapply() can also be used to apply a function to the environment. Here is the second function you could use if you don't like mget() . It can be used the same way as above, and this is probably the best 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) }