0

I am trying to write a function to clear the global environment in R since I am too lazy to type rm(list=ls(all=T)) every time.

I tried

purge = function(){
    rm(list=ls(all=T), envir = globalenv())
}

and

purge = function(){
    rm(list=ls(all=T), pos = 1)
}

but they don't seem to be doing anything. There is a similar question that is targeted to a single object here but all I want to do is to clear everything in one go every single time. (I realize this function will also be gone after that but that is not an issue)

Community
  • 1
  • 1
OganM
  • 2,543
  • 16
  • 33
  • 3
    `purge <- function(all = FALSE) rm(list = ls(.GlobalEnv, all.names = all), envir = .GlobalEnv)`, ie, you need to set the environment in `ls` also since it defaults to the current environment and not the global – rawr Nov 28 '14 at 03:12
  • Yup forgot about ls's arguments. Thanks – OganM Nov 28 '14 at 03:15
  • 1
    If you made it `.purge` (dot in front) and removed `all = TRUE` it wouldn't be removed when you called it. I wouldn't do `all = TRUE` personally, because you'd also be removing the `.Random.seed` – Rich Scriven Nov 28 '14 at 03:18
  • 1
    Another way to not delete the function is to put it in an environment and attach the environment to the search path: `local({MyFuns <- new.env(); MyFuns$purge <- function(all = FALSE) rm(list = ls(.GlobalEnv, all.names = all), envir = .GlobalEnv); attach(MyFuns)})` – GSee Nov 28 '14 at 03:34

0 Answers0