4

I'm trying to create a function that will, simultaneously, clear the workspace and the memory so that, rather than having to type "rm(list = ls()); gc()", I can type just one function. But rm(list = ls()) doesn't work when it's called from within a function. Why? Is there any way around this?

> # Let's create an object
> x = 0
> ls()
[1] "x"
> 
> # This works fine:
> rm(list = ls()); gc()
         used (Mb) gc trigger (Mb) max used (Mb)
Ncells 269975 14.5     592000 31.7   427012 22.9
Vcells 474745  3.7    1023718  7.9   808322  6.2
> ls()
character(0)
> 
> ## But if I try to create a function to do exactly the same thing, it doesn't work
> # Creating the object again
> x = 0
> ls()
[1] "x"
> 
> #Here's the function (notice that I have to exclude the function name from the 
# list argument or the function would remove itself):
> clear = function(list = ls()[-which(ls() == "clear")]){
+   rm(list = list); gc()
+ }
> ls()
[1] "clear" "x"    
> 
oguz ismail
  • 1
  • 16
  • 47
  • 69
Lucas De Abreu Maia
  • 598
  • 2
  • 6
  • 19
  • 2
    inside a function R creates a new environment for you - so it isn't working in the global environment – B Williams Oct 27 '17 at 03:08
  • 1
    a) you haven't run the function. b) inside a function, `rm` will only be evaluated in the scope of the function. So it won't delete anything in your global environment. See `?rm` and notice it has an `envir=` argument. – thelatemail Oct 27 '17 at 03:08

1 Answers1

8

rm is actually working, however since you're using it inside a function, it only removes all objects pertaining to the environment of that function.

Add envir = .GlobalEnv parameter to both calls:

rm(list = ls(envir = .GlobalEnv), envir = .GlobalEnv)

should do it.

I also recommend you take a look at this other question about gc() as i believe it's not a good practice to call it explicitly unless you really need it.

Diego Queiroz
  • 394
  • 8
  • 11