rm()
rm(..., list = character(), envir = as.environment(pos)) The rm() function removes one or more objects from the specified environment by name. It is commonly used to clean up temporary objects, free memory, or remove specific variables from the workspace.
Syntax
rm(..., list = character(), envir = as.environment(pos))
Parameters
| Parameter | Type | Default | Description |
|---|---|---|---|
... | names | , | Object names (unquoted) to remove |
list | character | character() | Character vector of object names to remove |
envir | environment | as.environment(pos) | Environment to remove objects from |
Examples
Basic usage
# Create some objects
x <- 1:10
y <- "hello"
z <- list(a = 1, b = 2)
# List objects in the environment
ls()
# [1] "x" "y" "z"
# Remove a single object
rm(x)
ls()
# [1] "y" "z"
When you need to clean up several objects at once, pass multiple names to rm() separated by commas. Each argument is an unquoted name, and all are removed in a single call. This is more efficient than calling rm() repeatedly for each object because R only updates the environment binding table once. The names are evaluated lazily, so you cannot pass the result of a function call — only literal object names or quoted strings work with the ... argument.
Removing multiple objects
# Remove multiple objects at once
rm(y, z)
ls()
# character(0)
# Create fresh objects
a <- 10
b <- 20
c <- 30
# Remove all at once using ...
rm(a, b, c)
ls()
# character(0)
The list parameter accepts a character vector of object names instead of unquoted arguments. This form is essential when you need to remove objects whose names are not known until runtime — for example, when names are stored in a variable, returned by ls(), or generated programmatically. Combining ls() with a pattern and rm(list = ...) lets you target groups of objects with a shared naming convention without enumerating each one individually.
Using the list parameter
# Create some objects
df <- data.frame(x = 1:5)
mat <- matrix(1:9, nrow = 3)
vec <- c(1, 2, 3)
# Remove using character vector
to_remove <- c("df", "mat")
rm(list = to_remove)
ls()
# [1] "vec"
By default, rm() operates on the global environment, but the envir argument lets you target any R environment. This is useful inside package code or when working with nested environments created by new.env(). Removing an object from a specific environment leaves the global workspace untouched, and you can verify the removal with ls(envir = target_env). The environment must be passed by reference, not by name — use the environment object directly, not a character string.
Cleaning up from a specific environment
# Create a new environment
my_env <- new.env()
my_env$temp <- 123
my_env$data <- iris
ls(my_env)
# [1] "temp" "data"
# Remove from specific environment
rm(temp, envir = my_env)
ls(my_env)
# [1] "data"
A common cleanup pattern keeps only a handful of important objects and removes everything else. The expression setdiff(ls(), c("keep1", "keep2")) computes the names of all objects except those on your keep list, and passing that to rm(list = ...) deletes the rest. This is more practical than listing every temporary object to remove, especially after an interactive session that produced dozens of intermediate variables. Just be careful to spell the keep-list correctly — a typo removes the wrong object with no undo.
Removing all objects except some
# Create many objects
x <- 1
y <- 2
z <- 3
keep <- "important"
# Remove all except "keep"
rm(list = setdiff(ls(), "keep"))
ls()
# [1] "keep"
Common patterns
Once you understand the basics of removing individual and groups of objects, a few recurring patterns cover most real-world uses. These patterns appear at the top of scripts, inside functions that manage temporary state, and in interactive sessions where you need to reset the workspace to a known starting point.
Clear the entire workspace
rm(list = ls())
This removes every visible object in the global environment, but objects whose names begin with a dot (like .myhidden) are not matched by ls() by default. To include hidden objects, use ls(all.names = TRUE). A safer variation restricts removal to .GlobalEnv explicitly, which avoids accidentally removing objects from attached packages or other environments that might share the same search path. The idiom rm(list = ls(envir = .GlobalEnv), envir = .GlobalEnv) clears only the global workspace while leaving everything else intact:
rm(list = ls(envir = .GlobalEnv), envir = .GlobalEnv)
After running a computation that produces large intermediate results, removing those temporary objects frees memory for subsequent steps. This is especially important in long-running scripts or R Markdown documents where intermediate objects accumulate but are never referenced again. Pairing rm() with gc() forces R to release the memory back to the operating system immediately rather than waiting for automatic garbage collection, which can make the difference between a script that runs within available RAM and one that exhausts it.
Remove temporary objects after analysis
# After computation
temp_result <- sum(rnorm(1000))
# Clean up when done
rm(temp_result)
Inside functions, temporary variables created during computation persist in the function’s evaluation environment until the function returns. While R’s garbage collector eventually reclaims this memory, explicitly removing large intermediates with rm() before the return() statement reduces peak memory usage during the function call. This matters most in recursive functions or functions called inside tight loops, where each invocation would otherwise hold its intermediates until the entire call stack unwinds.
Selective cleanup in functions
process_data <- function(df) {
# Intermediate calculations
temp_mean <- mean(df$value)
temp_sd <- sd(df$value)
# Return only final result
result <- list(mean = temp_mean, sd = temp_sd)
# Clean up intermediate values
rm(temp_mean, temp_sd)
return(result)
}
rm() in practice
rm() removes objects from the current environment, freeing the memory they hold. The change is immediate, after rm(x), any subsequent reference to x raises an error. In interactive sessions, rm(list = ls()) clears the entire workspace; this is a common first line in scripts that should start from a clean state.
rm() accepts either bare names or character strings via list: rm(x, y) and rm(list = c("x", "y")) are equivalent. The list form is useful when the variable names are computed: rm(list = ls(pattern = "^temp_")) removes all objects whose names start with temp_.
Removing an object does not necessarily immediately release memory to the operating system, R maintains its own memory pool and calls gc() (garbage collection) periodically. To force immediate garbage collection, call gc() after rm(). In practice, memory-intensive workflows use rm() + gc() after processing large intermediate objects to free memory before the next step.
rm() only removes bindings in the specified environment (default: .GlobalEnv). Objects in other environments (e.g., package namespaces, parent frames) are not affected. Use remove() as an alias, it is the same function with the same signature.
rm() removes objects from the current environment by name. Multiple objects can be removed in one call: rm(a, b, c) or rm(list = c("a", "b", "c")) (the latter form is required when names are computed at runtime). rm(list = ls()) removes everything in the current environment, equivalent to restarting with a clean workspace. Removed objects are not recoverable unless undo() is available in the development environment.
See also
- round()
- rep()
- rownames()
gc()afterrm()returns the freed memory to the operating system immediately rather than waiting for automatic garbage collection.rm(list = ls(pattern = "^temp"))removes all objects whose names start with “temp”. Theenvirargument targets a specific environment:rm("x", envir = parent.env(environment()))removes from the parent environment. In package development, avoid usingrm()to clean up after tests, usewithroron.exit()instead, which restore state even when an error occurs.rm(list = ls())at the start of a script is a common but controversial practice — it destroys all objects in the global environment.