Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to save a variable not removed by rm(list=ls())

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)

like image 398
RockScience Avatar asked Dec 12 '22 13:12

RockScience


2 Answers

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')
like image 74
Tommy Avatar answered Jan 04 '23 01:01

Tommy


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
like image 29
Chase Avatar answered Jan 04 '23 01:01

Chase