Reset R instance

后端 未结 2 681
無奈伤痛
無奈伤痛 2021-02-05 12:24

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 th

2条回答
  •  情话喂你
    2021-02-05 12:51

    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

提交回复
热议问题