A base R solution is:
# assign variables to global environment
a <- 1
b <- 2
c <- 3
d <- 4
e <- 5
ls()
#R> [1] "a" "b" "c" "d" "e"
# make function
remove_all_but <- function(...){
keep <- sapply(match.call(expand.dots = FALSE)$..., deparse)
rm(list = setdiff(ls(envir = .GlobalEnv), keep), envir = .GlobalEnv)
}
# use function
remove_all_but(a, b, c)
ls()
#R> [1] "a" "b" "c"
This also work even if remove_all_but
is not assigned in the global environment.
You can replace sapply(match.call(expand.dots = FALSE)$..., deparse)
with sapply(match.call()[-1], deparse)
.
We can make this slightly more general by allowing the user select the environment from which variables should be removed from:
# assign variables to an environment
ev <- new.env()
local(envir = ev, {
a <- 1
b <- 2
c <- 3
d <- 4
e <- 5
})
ls(envir = ev)
#R> [1] "a" "b" "c" "d" "e"
# make function
remove_all_but <- function(..., envir = .GlobalEnv){
keep <- sapply(match.call(expand.dots = FALSE)$..., deparse)
rm(list = setdiff(ls(envir = envir), keep), envir = envir)
}
# use function
remove_all_but(a, b, c, envir = ev)
ls(envir = ev)
#R> [1] "a" "b" "c"