Skip to content

Using rm in R by defining what you want to keep, rather than what you want to remove

August 1, 2012

The rm command in R is useful for removing objects from your workspace. The standard way to use it is to specify what you want to remove. But — being an optimist (sort of) — I often would rather specify what I want to keep. This probably isn’t the best way but its a pretty good way:


# start with a blank slate
rm(list = ls())

# add some stuff
x <- 1
y <- 2
z <- 3

# define what you want to keep
tokeep <- c('z','x')

# calculate what you want to remove
toremove <- setdiff(ls(), tokeep)

# remove what you want to remove, 
# as well as the vector containing
# the names of the stuff you want
# to remove (because presumably
# you don't want to keep that
# either)
rm(list = c(toremove, 'toremove'))

# print what you kept
# (should be 'x' and 'z')
ls()
Advertisements
No comments yet

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: