I would like to save a variable in R, that would not be removed by rm(list=ls())
I think it is possible as for instance installed functions and data from packages are not removed.
Edit: One possibility could be to set an env variable just for this R session. I have tried Sys.setenv(ENV_VAR = 1)
but Sys.getenv(ENV_VAR)
returns an error.
(I am on windows 32bits, R 2.12.1)
First, to get the environment variable you need to put quotes around it:
Sys.setenv(ENV_VAR = 1)
Sys.getenv("ENV_VAR")
Second, as Chase said, a 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 to detach it:
detach('myvars')
The proper answer involves putting your variable into a new environment. One quick and dirty trick is to prepend a .
in front of the variable so that it isn't picked up 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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With