If your R session contains old data frames, variables, or functions, it can be hard to tell which objects your code is using. Clearing the workspace gives you a clean starting point and can help prevent results from depending on leftover objects. In R, the usual way to clear the workspace is to remove objects from the global environment with rm(). You can do this in the R console, in an R script, or through RStudio’s Environment pane.
The right method depends on what you mean by “workspace.” Removing objects does not automatically unload packages, close plots, erase files, or reset every setting in R. This guide explains how to clear your R workspace safely, how to remove selected objects, and what to do when you need a completely fresh session.
What Does Clearing the Workspace in R Mean?
In R, a workspace is often used to mean the collection of objects available in an environment. These objects might include vectors, data frames, lists, models, and functions. When you work interactively, they are usually stored in the global environment, which is commonly shown in RStudio’s Environment pane.
Clearing the workspace typically means removing some or all of those objects. It does not mean deleting your R script or data files from your computer. It also does not necessarily reset your working directory, detach packages, close graphics devices, or erase command history. Knowing this distinction helps you choose the appropriate cleanup method.
How to Clear the Workspace in R with rm()
The most common command for clearing objects from the current environment is rm(). To remove every listed object from the global environment, run:
rm(list = ls())
The command combines two functions. ls() returns the names of objects in the current environment, and rm() removes the objects whose names you provide. In a standard interactive R session, the current environment is usually the global environment. After running the command, the Environment pane should no longer show those objects.
For a command that explicitly targets the global environment, use:
rm(list = ls(envir = .GlobalEnv), envir = .GlobalEnv)
Specifying .GlobalEnv makes the target clear, which is useful in scripts or when you are working with multiple environments. The command removes objects stored there without asking for confirmation, so check that you do not need them before running it.
How to Remove Hidden Objects Too
By default, ls() does not list names that begin with a period. These are often called hidden objects. If you want to remove all objects in the global environment, including hidden ones, use all.names = TRUE:
rm(list = ls(envir = .GlobalEnv, all.names = TRUE),
envir = .GlobalEnv)
This is a more thorough cleanup, but it can remove objects you may not have noticed. Use it deliberately, especially in a session where you or a package has created hidden objects. In most everyday cases, rm(list = ls()) is enough.
How to Clear the Workspace in RStudio
RStudio provides a graphical way to remove objects. Find the Environment pane, then click the broom icon, often labeled “Clear All.” Depending on your RStudio version and settings, you may see a prompt asking you to confirm. Accepting the prompt removes objects from the displayed environment.
The broom is convenient for interactive work, but it can be less transparent than a line of code. A command such as rm(list = ls()) can be saved in a script and reviewed later. If you use the RStudio control, confirm that you are clearing the intended environment and not one of several environments shown in the pane.
How to Remove Specific Objects Instead
You do not have to clear everything. To remove one object, pass its name to rm() without quotation marks:
rm(my_data)
To remove several objects, separate their names with commas:
rm(my_data, old_model, temporary_results)
You can also remove objects by name using a character vector. This is helpful when names are stored in another object or generated by code:
objects_to_remove <- c("my_data", "old_model")
rm(list = objects_to_remove)
Use selective removal when you want to free up clutter but keep important results. Before removing an object, check that it is not required by later code. If you are unsure, save important results to a file first, or rerun your analysis from a script after cleaning the environment.
How to Check What Is in Your Workspace
Before clearing the workspace, inspect its contents. The ls() function lists object names:
ls()
To see hidden names as well, run ls(all.names = TRUE). To learn more about a particular object, use class(), str(), or summary(). For example:
class(my_data)
str(my_data)
summary(my_data)
These checks can help you distinguish temporary objects from data or models you want to preserve. If you need a more detailed inventory, you can inspect the Environment pane in RStudio or review the objects by name before running a removal command.
Does rm() Free Memory in R?
Removing objects makes them unavailable in the environment, and R can then reclaim memory that is no longer in use. You can request garbage collection with:
gc()
Garbage collection asks R to identify and reclaim memory from objects that are no longer referenced. You do not usually need to run it after every removal; R manages memory automatically. Also, the memory shown as available to your operating system may not change immediately. Removing an object does not guarantee that all related memory will instantly be returned to the operating system.
How to Start with a Completely Fresh R Session
If you need more than an empty global environment, restart R. In RStudio, use the Session menu and choose “Restart R.” The common keyboard shortcut is Ctrl+Shift+F10 on Windows and Linux, or Command+Shift+F10 on macOS, although shortcuts can vary with settings and versions.
Restarting creates a new R session, clearing objects from memory and resetting session-level state. It is often the best choice when you are troubleshooting unexpected behavior or want to test whether a script runs from a clean start. A restart is different from closing and reopening your project files: your scripts and saved data files remain on disk.
RStudio may offer to restore a saved workspace when you open a project or start R. If you want a consistently clean session, review the project’s settings and your general RStudio preferences for workspace restoration and automatic saving. A saved .RData file can bring objects back into a later session if it is loaded.
What Clearing the Workspace Does Not Remove
The command rm(list = ls()) removes objects from the current environment. It does not perform a full reset of R. In particular, it does not usually:
- Unload packages that have been attached with
library(). - Delete scripts, datasets, or other files from your computer.
- Reset the current working directory or every option and setting.
- Close open graphics devices or erase plots already displayed.
- Clear the console or remove command history.
For plots, you can close graphics devices with graphics.off(), but this is separate from removing workspace objects. Be cautious with commands that close connections or alter settings, because they can interrupt other work. If you need to reset multiple parts of a session, restarting R is generally clearer than combining many unrelated cleanup commands.
Common Mistakes When Clearing an R Workspace
A frequent mistake is clearing the workspace and then expecting packages to be unloaded. Packages are attached to the search path, not stored as ordinary objects in the global environment. Another mistake is using rm(list = ls()) inside a function and expecting it to clear the global environment. Inside a function, ls() refers to the function’s environment unless you specify another environment.
To target the global environment from a function or other context, use an explicit environment:
rm(list = ls(envir = .GlobalEnv), envir = .GlobalEnv)
Also avoid adding a workspace-clearing command at the beginning of every script without considering how the script is run. It can erase objects that the user intentionally prepared. For reproducible analysis, it is usually better for a script to load its own inputs, create its own required objects, and save its outputs explicitly.
Best Practices for a Clean and Reproducible R Session
A clean workspace is useful, but repeatable code matters more than routinely deleting objects. Write scripts so they can run from beginning to end in a fresh session. Use clear object names, keep source code separate from data and output files, and save important results in a deliberate format such as RDS or CSV when appropriate.
When testing whether a script is self-contained, restart R and run the script from the top. If it fails because an object is missing, the script may depend on something created manually in an earlier session. Fixing that dependency makes the analysis easier to reproduce and share.
In a project, consider using project-specific settings and relative file paths rather than relying on objects left in memory or a particular working directory. Avoid saving and automatically restoring the entire workspace unless that behavior is intentional. These habits reduce confusion and make it easier to identify where results come from.
Frequently Asked Questions
What is the quickest way to clear the R workspace? Run rm(list = ls()) in the console. It removes the objects listed in the current environment, typically the global environment in an interactive session.
How do I clear everything, including hidden objects? Use rm(list = ls(all.names = TRUE), envir = .GlobalEnv) to remove hidden and visible objects from the global environment.
Will clearing the workspace delete my files? No. Removing R objects does not delete scripts or data files stored on your computer. It removes objects from memory.
Should I use rm() or restart R? Use rm() when you only want to remove objects. Restart R when you need a fresh session or want to reset session-level state more broadly.
Conclusion
To clear the workspace in R, the standard command is rm(list = ls()). For a more explicit cleanup of the global environment, use rm(list = ls(envir = .GlobalEnv), envir = .GlobalEnv), and add all.names = TRUE if you also want to remove hidden objects. You can use the RStudio broom icon for a quick graphical option, remove individual objects with rm(), or restart R when you need a genuinely fresh session. Choose the least disruptive method that matches your goal, and build scripts that can run reliably without depending on leftover workspace objects.
Disclaimer: Articles are written by Humans, AI or Both. Verify Important information.