Written and maintained by CASRAI Editorial Board
Published · Last updated
On this page
To clear the environment in R, run rm(list = ls(envir = .GlobalEnv, all.names = TRUE), envir = .GlobalEnv). This removes the objects named in the global workspace, including hidden names that begin with a dot. Preview that list first: deleting objects is different from restarting R, and it does not reset the whole session.
What it is used for in research
A research analysis can accumulate imported data, intermediate calculations, fitted models and helper functions. Removing selected objects lets you discard an intermediate result before rebuilding it. Clearing the global workspace has a broader purpose: it removes the objects your script might otherwise reuse from earlier interactive work.
For example, imagine an analysis script that calculates a result from an object called samples but never creates or imports samples itself. It might appear to work while that object remains in the workspace. Removing it exposes the missing dependency when the script reaches that expression. This is an illustrative software scenario, rather than a claim about any particular research project.
That check contributes to computational reproducibility, but an empty workspace alone does not establish it. The R manual defines the workspace as a collection of objects; the session also involves packages, options and startup behavior. Decide whether you need to remove particular objects or start another session before selecting a cleanup command.
Install or access R
The commands here use base R, so no additional cleanup package is needed. Open an R console, either directly or within RStudio. Posit’s Get Started guide links to the official R and RStudio installation routes; the CASRAI R and RStudio installation guide explains the platform choices.
Use help(rm), help(ls) and help(environment) in R to inspect the documentation that belongs to your installation. The important arguments are list, which supplies names to remove; envir, which identifies the target environment; and all.names, which controls whether ls includes dot-prefixed names. The same target should appear in both the listing and removal calls.
Save your analysis script and any outputs you intend to keep before removing their in-memory objects. R’s introductory manual distinguishes persistent files from workspace objects: an object that exists only in memory is not a saved analysis script or an exported result.
Step-by-step: clear the global environment in R
-
Inspect the target. Run
ls(envir = .GlobalEnv, all.names = TRUE). Read the returned names before continuing. This includes user functions and dot-prefixed objects, rather than only the ordinary data names you may recognize. -
Choose the scope. To remove one object, use
rm(samples, envir = .GlobalEnv). To remove several known objects, userm(list = c('samples', 'temporary_fit'), envir = .GlobalEnv). Substitute names that actually belong to your analysis. -
Remove the complete listed workspace only when that is your intent. Run
rm(list = ls(envir = .GlobalEnv, all.names = TRUE), envir = .GlobalEnv). The inner call generates names; the outer call removes those names from the same environment. -
Check immediately. Run
ls(envir = .GlobalEnv, all.names = TRUE)again. An empty character vector, displayed ascharacter(0), means that listing found no names in the global environment at that point. -
Rebuild the analysis from its inputs. Run the script’s import and preparation steps before calculations that use their results. For file-based inputs, the RStudio dataset import guide covers the import stage. Do not recreate a missing object manually just to hide a dependency error.
The frequently shown shortcut rm(list = ls()) uses the current environment and the default listing behavior. At the console it generally targets the workspace, but ls omits dot-prefixed names by default. Inside a function, its default target is that function’s local environment. Naming .GlobalEnv explicitly avoids making those two situations look equivalent.
R documents remove and rm as identical functions. The list argument matters: when a character vector contains object names, pass it through list rather than assuming that putting the vector in an unnamed argument will remove its named targets.
Output and how to read it
Use the second object listing as the evidence of removal. A console that no longer shows earlier printed output is a different observation from a workspace whose names have been removed. Likewise, a script can remain open in the editor while its data objects no longer exist.
Interpret character(0) narrowly. It describes the selected environment, rather than every package, namespace, nested environment or resource associated with the R process. R’s Environment Access documentation explains that environments contain named objects and a link to an enclosing environment. Clearing one frame does not recursively empty that entire structure.
If you call gc(), its output is a memory report, with Ncells and Vcells rows and columns describing usage and collection thresholds. It is not an alternative object listing. R already performs garbage collection automatically; a manual call after removing a large object may encourage memory to return to the operating system, without guaranteeing a particular reduction.
Worked example: keep a result, remove temporary data
This synthetic, illustrative composite uses four sample counts to demonstrate selective cleanup. The values are teaching inputs, not observations from a study. Run the following expressions in order in a disposable analysis session:
-
samples = data.frame(sample_id = c('A', 'B', 'C', 'D'), count = c(12, 18, 24, 30)) -
.temporary_counts = samples$count -
mean_count = mean(.temporary_counts) -
mean_count -
ls(envir = .GlobalEnv, all.names = TRUE) -
rm(list = c('samples', '.temporary_counts'), envir = .GlobalEnv) -
mean_count
The mean is 21: the sum 12 + 18 + 24 + 30 is 84, divided by four observations. The last expression still evaluates to 21 because this cleanup names only samples and .temporary_counts. It deliberately preserves mean_count. Other objects already in the session also remain; this example is not a complete workspace reset.
Now compare ls(envir = .GlobalEnv) with ls(envir = .GlobalEnv, all.names = TRUE) before removing the temporary objects in another run. The second listing includes .temporary_counts; the first omits it. That contrast makes the hidden-name issue visible without needing a large dataset or a memory benchmark.
Clear a separate analysis environment
An explicit environment lets you target a task’s objects separately. In another illustrative example, run these expressions in order:
-
analysis = new.env(parent = baseenv()) -
analysis$counts = c(12, 18, 24, 30) -
ls(envir = analysis, all.names = TRUE) -
rm(list = ls(envir = analysis, all.names = TRUE), envir = analysis) -
ls(envir = analysis, all.names = TRUE)
The final listing is empty, but the global object named analysis still refers to the environment. This illustrates a useful distinction: removing bindings inside an environment differs from removing the name that refers to that environment. The target in the two nested calls is analysis, rather than .GlobalEnv.
Troubleshooting
Objects with dots remain after cleanup
Check all.names in the listing expression. The documented default is FALSE, which excludes names beginning with a dot. Use TRUE in the preview, removal and verification expressions when those names are part of the intended cleanup. A plain ls() result cannot demonstrate that hidden names are absent.
The command clears the wrong environment
Check whether the expression is running inside a function. Both ls and rm normally operate in the current environment. Explicitly supply the intended frame to each call, as in the separate-environment example. Avoid using inherits = TRUE to pursue names through enclosing environments as a general cleanup strategy; the ordinary default is FALSE.
A warning about a missing object can mean that the name is absent from the selected frame. Confirm the spelling and preview that frame instead of broadening the deletion indiscriminately. Locked environments and the base environment have removal restrictions documented by rm; they are not targets for workspace housekeeping.
A helper function disappears along with the data
A function you defined in the workspace is also an object. A complete workspace removal does not distinguish an imported dataset from a helper function merely because they serve different purposes. If a later line cannot find your helper, rerun its definition from the saved script before calling it.
For an illustrative check, define twice = function(x) x * 2 and call twice(3), which returns 6. Then remove it with rm(twice, envir = .GlobalEnv). The function’s name is now absent from that frame just as a data object’s name would be. This is why selective cleanup should name disposable intermediates, while a full cleanup should be followed by the script that defines both the data and the functions it needs.
Objects return when R starts again
R can restore .RData at startup, while startup profiles can also execute code. Posit’s guide describes Tools > Global Options: turn off workspace restoration and choose Never for saving the workspace on exit when your intended workflow rebuilds objects from scripts. Review Project Options too, because project settings can override the global choices.
The Startup documentation distinguishes .Renviron files, which set operating-system environment variables, from .Rprofile files, which contain R code. These are separate from the named R objects removed by rm. Do not treat editing startup configuration or deleting environment variables as another spelling of clearing the workspace.
An empty workspace does not resolve the error
Restart the R session when the question concerns session state beyond object names. RStudio provides the Restart R Session command. For command-line work, R --vanilla starts R with documented startup and restore options disabled. This also skips initialization your project may rely on, so declare required setup explicitly before interpreting an error.
A fresh run is a diagnostic check, not proof that the analysis is correct. Record which inputs and setup steps the script needs, then run them in order. Removing the evidence of an earlier error without repairing its cause will not make the workflow reproducible.
Free alternatives for managing R objects
The alternatives here are built-in R mechanisms, rather than additional cleanup products. They solve different tasks. Choose according to whether you want to delete a binding, prevent temporary names from escaping their calculation, or begin a new process with startup isolation.
| Alternative | Task it addresses | Scope to understand |
|---|---|---|
remove(samples, envir = .GlobalEnv) |
Delete a selected workspace object | Identical function to rm, so it does not provide a broader reset |
local({ temporary = c(12, 18, 24, 30); mean(temporary) }) |
Evaluate temporary calculations in a local environment | Returns the calculation’s value without creating that temporary name in the global frame |
R --vanilla |
Start a command-line session without the usual restore and initialization files | A new session, with different startup behavior from an ordinary launch |
These entries follow the rm, local and startup documentation. For repeated calculations, local scope is a design choice that reduces the need for later global cleanup; it does not retroactively remove objects already created elsewhere. The data table below separately compares the targets and checks for common cleanup operations, including hidden-name listing and garbage collection.
Sources
- R Core: Remove Objects from a Specified Environment. Checked 2026-11-14.
- R Core: List Objects. Checked 2026-11-14.
- R Core: Environment Access. Checked 2026-11-14.
- R Core: Garbage Collection. Checked 2026-11-14.
- R Core: Initialization at Start of an R Session. Checked 2026-11-14.
- R Core: Evaluate an (Unevaluated) Expression, including local. Checked 2026-11-14.
- R Core: An Introduction to R. Checked 2026-11-14.
- Posit: RStudio Projects. Checked 2026-11-14.
- Posit: Get Started. Checked 2026-11-14.
- Posit: Keyboard Shortcuts. Checked 2026-11-14.
Data: R environment cleanup operations and verification
Original cross-reference compiled from R Core documentation for object listing, removal, environment access, garbage collection and startup. It separates each operation’s target, documented effect and scope of verification; these are function semantics, not measured performance results.
| Operation | Target | Documented effect | Verification or limit | Primary source URLs |
|---|---|---|---|---|
| ls(envir = .GlobalEnv, all.names = TRUE) | Global frame | Lists object names, including names starting with a dot | Inspection only; does not remove objects | https://stat.ethz.ch/R-manual/R-devel/library/base/html/ls.html |
| rm(list = c('samples', 'temporary_fit'), envir = .GlobalEnv) | Named objects in global frame | Removes only the supplied names from the selected environment | Preview that frame with ls; inherits defaults to FALSE | https://stat.ethz.ch/R-manual/R-devel/library/base/html/rm.html |
| rm(list = ls(envir = .GlobalEnv, all.names = TRUE), envir = .GlobalEnv) | Names listed in global frame | Removes the listed bindings, including dot-prefixed names | Repeat the same ls call; this checks the selected frame only | https://stat.ethz.ch/R-manual/R-devel/library/base/html/rm.html ; https://stat.ethz.ch/R-manual/R-devel/library/base/html/ls.html |
| rm(list = ls(envir = analysis, all.names = TRUE), envir = analysis) | A separate environment named analysis | Removes names inside that environment | The referring global name analysis remains | https://stat.ethz.ch/R-manual/R-devel/library/base/html/rm.html ; https://stat.ethz.ch/R-manual/R-devel/library/base/html/environment.html |
| gc() | R memory management | Performs garbage collection and reports memory usage | Automatic collection also occurs; no fixed memory-return guarantee | https://stat.ethz.ch/R-manual/R-devel/library/base/html/gc.html |
| R --vanilla | New command-line session | Disables workspace restore and specified startup files | Startup behavior differs from the usual session initialization | https://stat.ethz.ch/R-manual/R-devel/library/base/html/Startup.html |
Sources
- R Core: List Objects (accessed 2026-11-14)
- R Core: Remove Objects from a Specified Environment (accessed 2026-11-14)
- R Core: Environment Access (accessed 2026-11-14)
- R Core: Garbage Collection (accessed 2026-11-14)
- R Core: Initialization at Start of an R Session (accessed 2026-11-14)
Compiled by CASRAI from the sources above. Free to reuse under CC BY 4.0 with attribution.







