Skip to main content
v2026.11,986 entries · CC-BY 4.0

Clear Environment in R: Commands and Checks

Remove R workspace objects deliberately, check hidden names and separate object cleanup from restarting an analysis session.

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

  1. 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.

  2. Choose the scope. To remove one object, use rm(samples, envir = .GlobalEnv). To remove several known objects, use rm(list = c('samples', 'temporary_fit'), envir = .GlobalEnv). Substitute names that actually belong to your analysis.

  3. 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.

  4. Check immediately. Run ls(envir = .GlobalEnv, all.names = TRUE) again. An empty character vector, displayed as character(0), means that listing found no names in the global environment at that point.

  5. 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:

  1. samples = data.frame(sample_id = c('A', 'B', 'C', 'D'), count = c(12, 18, 24, 30))

  2. .temporary_counts = samples$count

  3. mean_count = mean(.temporary_counts)

  4. mean_count

  5. ls(envir = .GlobalEnv, all.names = TRUE)

  6. rm(list = c('samples', '.temporary_counts'), envir = .GlobalEnv)

  7. 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:

  1. analysis = new.env(parent = baseenv())

  2. analysis$counts = c(12, 18, 24, 30)

  3. ls(envir = analysis, all.names = TRUE)

  4. rm(list = ls(envir = analysis, all.names = TRUE), envir = analysis)

  5. 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

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.

R environment cleanup operations and verification
OperationTargetDocumented effectVerification or limitPrimary source URLs
ls(envir = .GlobalEnv, all.names = TRUE)Global frameLists object names, including names starting with a dotInspection only; does not remove objectshttps://stat.ethz.ch/R-manual/R-devel/library/base/html/ls.html
rm(list = c('samples', 'temporary_fit'), envir = .GlobalEnv)Named objects in global frameRemoves only the supplied names from the selected environmentPreview that frame with ls; inherits defaults to FALSEhttps://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 frameRemoves the listed bindings, including dot-prefixed namesRepeat the same ls call; this checks the selected frame onlyhttps://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 analysisRemoves names inside that environmentThe referring global name analysis remainshttps://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 managementPerforms garbage collection and reports memory usageAutomatic collection also occurs; no fixed memory-return guaranteehttps://stat.ethz.ch/R-manual/R-devel/library/base/html/gc.html
R --vanillaNew command-line sessionDisables workspace restore and specified startup filesStartup behavior differs from the usual session initializationhttps://stat.ethz.ch/R-manual/R-devel/library/base/html/Startup.html

Sources

Compiled by CASRAI from the sources above. Free to reuse under CC BY 4.0 with attribution.

Follow CASRAI

Research-administration guidance, standards updates and independent tool reviews.

Ask CASRAI · free to try

Ask about Clear Environment in R: Commands and Checks

Ask your first 2 questions free below. Subscribers get 150 a day for $29 a month.

An AI assistant specialized in research administration. It cites the sources behind every answer, labels web answers and says when it can't answer.

Answers draw on CASRAI's guides and dictionary plus the federal and funder documents we index: Federal Register, Grants.gov, Regulations.gov and UKRI.

Works on this site and inside Claude, Cursor and the AI tools you already use.

Everything CASRAI publishes — this page, the dictionary, the guides and the news — stays free to read, with no account and no card.

Referenced across the research world

University of Cambridge logoColumbia University logoCrossref logoUniversity of Edinburgh logoHarvard University logoUniversity of Oxford logoPrinceton University logoStanford School of Medicine logoUniversity College London logoORCID logoUniversity of Cambridge logoColumbia University logoCrossref logoUniversity of Edinburgh logoHarvard University logoUniversity of Oxford logoPrinceton University logoStanford School of Medicine logoUniversity College London logoORCID logo
  • University of Cambridge logo
  • Columbia University logo
  • Crossref logo
  • University of Edinburgh logo
  • Harvard University logo
  • University of Oxford logo
  • Princeton University logo
  • Stanford School of Medicine logo
  • University College London logo
  • ORCID logo

View CASRAI adoption →