Remove objects in .GlobalEnv from within a function

前端 未结 3 1800
庸人自扰
庸人自扰 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: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"
    

提交回复
热议问题