Reputation: 3973
How can I write a generic R function that cleans the current workspace apart from some self-defined variables? For sure, I can achieve this in a single script with the following code:
prj = '/path/to/project'
src = 'string'
data_to_clean = head(iris)
rm(list = ls()[ !ls() %in% c('prj', 'src') ] )
# only prj and src remain
However I want this to be a function, so that it's applicable for multiple scripts and I can change the variables which should not be cleaned, in one place. Is this possible?
Upvotes: 2
Views: 71
Reputation: 3175
I think you want to remove the function itself. The important bit is to tell rm
the environment where to remove these objects from:
clean_workspace <- function(not_to_be_removed, envir = globalenv()) {
objs <- ls(envir = envir)
rm(list = objs[ !objs %in% not_to_be_removed], envir = envir)
}
prj = '/path/to/project'
src = 'string'
data_to_clean = head(iris)
clean_workspace(c('prj', 'src'))
ls()
#> [1] "prj" "src"
Upvotes: 1
Reputation: 10350
In case you wrap this in a function, you have to keep in mind, that a function will create its own environment, when executed. Therefore, you need to specify the environment every time (in each ls
as well as rm
). You probably want to remove them from the .GlobalEnv
.
clean_workspace <- function(not_to_be_removed) {
rm(list =
setdiff(ls(envir = .GlobalEnv), c("clean_workspace", not_to_be_removed)),
envir = .GlobalEnv)
}
prj = '/path/to/project'
src = 'string'
data_to_clean = head(iris)
clean_workspace(c('prj', 'src'))
In order not to remove the function itself, it should be added to the values not to be removed.
If you want to read more about environments, have a look a this overview.
Upvotes: 1