user36800
user36800

Reputation: 2259

Function to remove all variables

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.

Upvotes: 2

Views: 1135

Answers (1)

David Robinson
David Robinson

Reputation: 78600

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
    )
}

Upvotes: 9

Related Questions