Removing all but several items from the global environment

I am trying to create a function to remove all but one to three items from the global environment. I am able to do it for one but not for two, three or more. Would appreciate any help on this using base R or rlang

a <- "a"
b <- c(1,2,3,4)
c <- c("M", "F")
remove_all_but <- function(x){
  Sx <- deparse(substitute(x))
  rm(list=Sx,envir=sys.frame(-1))
}

remove_all_but(a)

remove_all_but(c(a, b))
#> Warning in rm(list = Sx, envir = sys.frame(-1)): object 'c(a, b)' not found

If you can stand to quote the object names, this seems to work.

MyFunc <- function(obs) {
  obs <- paste0("^", obs, "$", collapse = "|")
  rm(list = ls(name = 1)[!grepl(obs, ls(name = 1))], pos = 1)
}

MyFunc(c("a", "b", "c"))

Notice that this will also remove MyFunc from the global environment if that is where it lives.

1 Like

Thanks so much, @FJCC. This is really helpful. It gave me some ideas in addition to other things I have also seen and it seems to work.

MyFunc <- function(...) {
  names <- as.character(rlang::enexprs(...))
  rm(list=setdiff(ls(pos=1), names), pos=1)
}
1 Like

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.