Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove objects in .GlobalEnv from within a function

Tags:

r

environment

I would like to create a function (CleanEnvir) which basically calls remove/rm and which removes certain objects from .GlobalEnv.

  CleanEnvir <- function(pattern = "tmp"){
      rm(list = ls()[grep("tmp", ls())], envir = globalenv())
  }

  keep <- 1
  tmp.to.be.removed <- 0
  ls()

  ## does not work
  CleanEnvir()
  ls()

  ## does work
  rm(list = ls()[grep("tmp", ls())], envir = globalenv())
  ls()
like image 974
Bernd Weiss Avatar asked Jan 29 '11 14:01

Bernd Weiss


1 Answers

ls() needs to look in the correct place. By default it looks in the current frame, that of the function CleanEnvir in your case and hence was only finding "pattern" in your original.

CleanEnvir <- function(pattern = "tmp") {
    objs <- ls(pos = ".GlobalEnv")
    rm(list = objs[grep("tmp", objs)], pos = ".GlobalEnv")
}

Which gives:

> CleanEnvir <- function(pattern = "tmp") {
+     objs <- ls(pos = ".GlobalEnv")
+     rm(list = objs[grep("tmp", objs)], pos = ".GlobalEnv")
+ }
> ls()
[1] "CleanEnvir"        "foo"               "keep"             
[4] "tmp.to.be.removed"
> CleanEnvir()
> ls()
[1] "CleanEnvir" "foo"        "keep"
like image 159
Gavin Simpson Avatar answered Oct 15 '22 09:10

Gavin Simpson