Exclude a specific type of object from the global environment

I have many different objects loaded into my global environment. How can I exclude only data frames and save 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, this did not work)

 remove(pattern="*.Rdata") 
+6
source share
1 answer

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:

 ## -- 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 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) } 
+8
source

Source: https://habr.com/ru/post/981525/


All Articles