Remove objects in .GlobalEnv from within a function

前端 未结 3 1801
庸人自扰
庸人自扰 2021-02-07 16:35

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

  Cle         


        
相关标签:
3条回答
  • 2021-02-07 17:08

    You need to do your search in the Global Env as well as the removal there:

    CleanEnvir <- function(pattern = "tmp"){
          rm(list = ls(envir=globalenv())[
                 grep("tmp", ls(envir=globalenv()))], envir = globalenv())
      }
    
    0 讨论(0)
  • 2021-02-07 17:16

    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"
    
    0 讨论(0)
  • 2021-02-07 17:17

    Shortest code solution I got for this is this one:

    remove a specific variable:

    y <- TRUE
    
    CleanEnvir <- function(x) {rm(list=deparse(substitute(x)),envir=.GlobalEnv)}
    
    CleanEnvir(y)
    y
    

    deparse substitute to paste the variable name rather than its value, and indeed pos = ".GlobalEnv" works, but you can also simply use envir=.GlobalEnv

    SOLUTION 2: This actually allows for pattern matching. (I STRONGLY recommend against this because you could possibly remove stuff you don't want to remove by accident. I.e. you want to remove tmp1 and tmp2 but you forgot that there is another variable that is called Global.tmp and localtmp as in temperature for example.

    remove by pattern:

    myvar1 <- TRUE
    myvar2 <- FALSE 
    
    Pat.clean.Envir <- function(x) { rm(list = ls(.GlobalEnv)[grep(deparse(substitute(x)), ls(.GlobalEnv))], envir = .GlobalEnv) }
    
    Pat.clean.Envir(myvar)
    

    cheers.

    0 讨论(0)
提交回复
热议问题