Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Function to remove all variables

Tags:

r

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.

like image 776
user36800 Avatar asked Mar 14 '26 15:03

user36800


1 Answers

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
    )
}
like image 145
David Robinson Avatar answered Mar 16 '26 06:03

David Robinson



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!