How to save a variable not deleted with rm (list = ls ())

I would like to save a variable in R that will not be deleted rm(list=ls())

I think this is possible, since, for example, installed functions and data from packages are not deleted.

Edit: One possibility would be to set the env variable only for this R session. I tried Sys.setenv(ENV_VAR = 1) , but Sys.getenv(ENV_VAR) returns an error.

(I'm on windows 32bits, R 2.12.1)

+4
source share
3 answers

First, to get the environment variable, you need to put quotation marks there:

 Sys.setenv(ENV_VAR = 1) Sys.getenv("ENV_VAR") 

Secondly, as Chase said, the new environment is the way to go, but you must also attach it:

 e <- new.env() e$foo <- 42 attach(e, name='myvars') rm(list=ls()) # Remove all in global env foo # Still there! 

... and disconnect it:

 detach('myvars') 
+6
source

The correct answer involves moving the variable to a new environment. One quick and dirty trick is to add . before the variable so that it is not raised by ls() .

 > x <- 1:10 > x [1] 1 2 3 4 5 6 7 8 9 10 > .x <- x > ls() [1] "x" > rm(list = ls()) > ls() character(0) > .x [1] 1 2 3 4 5 6 7 8 9 10 
+4
source

Another variant:

 # make busy workspace x<-1 y<-2 z<-3 > ls() [1] "x" "y" "z" # determine what to keep save<-"x" #discard the rest rm(list=ls()[!(ls()%in%save)]) > ls() [1] "x" 
+2
source

All Articles