2

From remove all variables except functions, I got the command to remove all variables without removing functions. I don't want to type it in all the time, so I tried to turn it into a function defined in ~/.Rprofile. I'm new to R, but I've browsed the environment frame scheme, and have a shaky understanding of it. The following attempt doesn't seem to erase a time series object defined in the main environment (the command line prompt when I first start R):

# In ~/.Rprofile
clVar <- function()
{
    rm(
        list=setdiff( ls(all.names=TRUE), lsf.str(all.names=TRUE)),
        envir=parent.frame()
    )
}

The following code shows that it doesn't work:

( x<-ts( 1:100 ,frequency=12 ) )
clVar()
ls()

Thanks for any help in fixing the environment framing.

Community
  • 1
  • 1
user36800
  • 2,019
  • 2
  • 19
  • 34

1 Answers1

9

You need to pass the parent.frame() environment to ls, not just to rm. Otherwise ls won't find the variables to remove.

clVar <- function()
{
    env <- parent.frame()
    rm(
        list = setdiff( ls(all.names=TRUE, env = env), lsf.str(all.names=TRUE, env = env)),
        envir = env
    )
}
David Robinson
  • 77,383
  • 16
  • 167
  • 187
  • I just figured it out! But thanks! By the way, I can't seem to mark this response as an answer for another 5 minutes. Strange why there would be a minimal time. – user36800 Apr 20 '15 at 20:52
  • @user36800 Cool! Reason behind time limit is [here](http://meta.stackexchange.com/questions/38090/discourage-questions-being-marked-as-answered-within-an-hour-or-so-of-being-poste) – David Robinson Apr 20 '15 at 21:02
  • 2
    I never knew that ensuring quality on stack exchange could be so...thoroughly thought out. Thanks. – user36800 Apr 22 '15 at 02:09