Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

rm( ) everything except specific object

Does someone have an idea about how can I remove everything in R except one object? Normally, to remove everything I code:

rm(list=ls())

So I tried:

rm(c(list=ls()-my_object))

but it didn’t work.

like image 239
Carlos Biagolini Avatar asked Sep 02 '26 10:09

Carlos Biagolini


1 Answers

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"
like image 52
SymbolixAU Avatar answered Sep 05 '26 00:09

SymbolixAU



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!