Clear the environment in R

Before starting a new project or initiating a new work session in R, it is recommended to clean up the environment. This means removing all objects and detaching all packages installed during the previous session.

The simplest and most reliable way to clean up the entire environment is to restart R, taking care not to save the current R image when closing the application. In RStudio, you must set the option Save workspace to .RData on exit to Never and disable the option to restore the environment on restart.

You should also make sure that there are no remaining .RData files in your project’s folder. These files are invisible, so you’ll need to use the command line to check if such files exist and, if they do, delete them.

Clear the environment without restarting R

It is also possible to put the R environment in a clean state using code. However, no method can guarantee to leave the environment as clean as it is when you initialize R. If you want some way to detach all packages except the basic ones, you can create a function - DetachPackages that automates this task.

This function creates a vector of basic package names that you should prevent from detaching. Then it creates a list with all the installed package names and subtracts from this list the names in the basic list. Finally, it detaches the packages whose names remain in the package.list.

DetachPackages <- function() {
    basic.packages <- c("package:stats","package:graphics","package:grDevices","package:utils","package:datasets","package:methods","package:base")
    package.list <- search()[ifelse(unlist(gregexpr("package:",search()))==1,TRUE,FALSE)]
    package.list <- setdiff(package.list,basic.packages)
    if (length(package.list)>0) {
        for (package in package.list) {
            detach(package, character.only=TRUE)
        }
    }
}

You can try this function by first installing and loading a package such as readxl with these commands:

install.packages("readxl")
library(“readxl”)

If you then execute sessionInfo(), in the other attached packages section, you will get this as part of the output:

other attached packages:
[1] readxl_1.3.1

Then you can call the DetachPackages() function, and call again sessionInfo(). The other attached packages section will be gone.

Related Article - R Packages