How do I clear only a few specific objects from the workspace?
You'll find the answer by typing ?rm
rm(data_1, data_2, data_3)
How can I remove all objects but one from the workspace in R?
Here is a simple construct that will do it, by using setdiff
:
rm(list=setdiff(ls(), "x"))
And a full example. Run this at your own risk - it will remove all variables except x
:
x <- 1
y <- 2
z <- 3
ls()
[1] "x" "y" "z"
rm(list=setdiff(ls(), "x"))
ls()
[1] "x"
clear everything but one variable rm(list = ls())
Try: rm(list = setdiff(ls(), x))
Edit based on mickey's comment:
Three objects in environment:
ls()
[1] "data_df" "list_ls" "vector_v"
Remove data_df:
rm(list = setdiff(ls(), "data_df"))
ls()
[1] "data_df"
Vector of things to keep:
toKeep_v <- c("list_ls", "vector_v")
rm(list = setdiff(ls(), toKeep_v)
ls()
[1] "list_ls" "vector_v"
Removing workspace objects whose name start by a pattern using R
The pattern argument uses regular expressions. You can use a caret ^
to match the beginning of the string:
rm(list=ls(pattern="^tp_"))
rm(list=setdiff(ls(pattern = "^tp_"), lsf.str()))
However, there are other patterns for managing temporary items / keeping clean workspaces than name prefixes.
Consider, for example,
temp<-new.env()
temp$x <- 1
temp$y <- 2
with(temp,x+y)
#> 3
rm(temp)
Another possibility is attach(NULL,name="temp")
with assign
.
R Global Function to Clear Workspace and Dump Storage
Two thoughts about this: Your code does not delete all objects, to also remove the hidden ones use
rm(list = ls(all.names = TRUE))
There is also the command gctorture()
which provokes garbage collection on (nearly) every memory allocation (as the man page said). It's intended for R developers to ferret out memory protection bugs:
cleaner <- function(){
# Turn it on
gctorture(TRUE)
# Clear workspace
rm(list = ls(all.names = TRUE, envir=sys.frame(-1)),
envir = sys.frame(-1))
# Turn it off (important or it gets very slow)
gctorture(FALSE)
}
If this procedure is used within a function, there is the following problem: Since the function has its own stack frame, only the objects within this stack frame are deleted. They still exist outside. Therefore, it must be specified separately with sys.frame(-1)
that only the higher-level stack frame should be considered. The variables are then only deleted within the function that calls cleaner()
and in cleaner
itself when the function is exited.
But this also means that the function may only be called from the top level in order to function correctly (you can use sys.frames()
which lists all higher-level stack frames to build something that also avoids this problem if really necessary)
rm(list=ls()) doesn't completely clear the workspace
attach()
does not make copies of x
and y
in your global environment, it attaches a dataframe to the search path.
From ?attach
:
The database is not actually attached. Rather, a new environment
is created on the search path and the elements of a list
(including columns of a data frame) or objects in a save file or
an environment are _copied_ into the new environment. If you use
‘<<-’ or ‘assign’ to assign to an attached database, you only
alter the attached copy, not the original object. (Normal
assignment will place a modified version in the user's workspace:
see the examples.) For this reason ‘attach’ can lead to
confusion.
For example:
> search()
[1] ".GlobalEnv" "package:stats" "package:graphics"
[4] "package:grDevices" "package:utils" "package:datasets"
[7] "package:methods" "Autoloads" "package:base"
> a <- data.frame(stuff=rnorm(100))
> search()
[1] ".GlobalEnv" "package:stats" "package:graphics"
[4] "package:grDevices" "package:utils" "package:datasets"
[7] "package:methods" "Autoloads" "package:base"
> attach(a)
> search()
[1] ".GlobalEnv" "a" "package:stats"
[4] "package:graphics" "package:grDevices" "package:utils"
[7] "package:datasets" "package:methods" "Autoloads"
[10] "package:base"
> rm(list=ls())
> search()
[1] ".GlobalEnv" "a" "package:stats"
[4] "package:graphics" "package:grDevices" "package:utils"
[7] "package:datasets" "package:methods" "Autoloads"
[10] "package:base"
> stuff
[1] -0.91436377 0.67397624 0.62891651 -0.99669584 2.07692590 -0.62702302
[...]
> detach(a)
> search()
[1] ".GlobalEnv" "package:stats" "package:graphics"
[4] "package:grDevices" "package:utils" "package:datasets"
[7] "package:methods" "Autoloads" "package:base"
rm( ) everything except specific object
The setdiff()
function shows the difference between sets, so we can use this to give the difference between all the objects (ls()
), and the object you want to keep. For example
## create some objects
df <- data.frame()
v <- as.numeric()
# show everything in environment
objects()
# [1] "df" "v"
## or similarly
ls()
# [1] "df" "v"
## the setdiff() funciton shows the difference between two sets
setdiff(ls(), "df")
# [1] "v"
# so we can use this to remove everything except 'df'
rm(list = setdiff(ls(), "df"))
objects()
# [1] "df"
How to remove all user created variables that start with a specific set of strings
You can probably do this using a regular expression via ls
:
rm(list = ls(pattern = "^tmp"))
Related Topics
Split One Row into Multiple Rows
How to Pass Command-Line Arguments When Calling Source() on an R File Within Another R File
How to 'Print' or 'Cat' When Using Parallel
How to Access and Edit Rprofile
Multiple Time Series in One Plot
R's Read.CSV Prepending 1St Column Name with Junk Text
Looping Through T.Tests for Data Frame Subsets in R
Converting a Character String into a Date in R
What's the Difference Between '=' and '<-' in R
Selecting Columns in R Data Frame Based on Those *Not* in a Vector
Change Values in Multiple Columns of a Dataframe Using a Lookup Table
Plotting Pca Biplot with Ggplot2
Removing Multiple Columns from R Data.Table with Parameter for Columns to Remove
R: Lm() Result Differs When Using 'Weights' Argument and When Using Manually Reweighted Data
Modify X-Axis Labels in Each Facet
How to Use Subscripts in Ggplot2 Legends [R]