Reset R instance

Viewed 17201

Is it possible to reset an instance of R?

Eg. if I have used the commands

x <- 1:10
plot(x, -x)

And thus polluted the system with the x variable. In this state can I then revert back to a clean state without shutting R down and launching it again?

2 Answers

Basing on the response of @Richie Cotton, comments and more, I think it's worth to consider five elements:

  1. Remove all objects
  2. Unload non-native packages
  3. Close all connections
  4. Restore the default options
  5. Close all graphic devices

So, there it is my simple ResetR function:

ResetR = function() {

    # 1) Remove all objects
    rm(list = ls(all=TRUE, envir = .GlobalEnv), envir = .GlobalEnv)

    # 2) Unload non-native packages. 
    nat = c(".GlobalEnv", "package:datasets", "package:evd", "package:nortest", "package:MASS", "package:stats", "package:graphics", "package:grDevices", "package:utils", "package:methods", "Autoloads", "package:base")

    p = search()
    for (i in p) {
        if (is.na(match(i, nat))) {
            try(eval(parse(text=paste0("detach(", i, ", unload=T, force=T)"))), silent=T) # force=T is need in case package has dependency
        }
    }

    # 3) Close all connections
    try(closeAllConnections(), silent=T)

    # 4) Restore default options
    try(options(baseenv()$.Options2), silent=T) # Remember to put assign(".Options2", options(), baseenv()) at the bottom of YOUR_R_HOME\etc\Rprofile.site

    # 5) Close all graphic devices
    graphics.off()

}

hth

Related