[R] How to remove all objects except a few specified objects?

Barry Rowlingson b.rowlingson at lancaster.ac.uk
Tue Aug 24 10:55:58 CEST 2010


2010/8/24 500600 <romunov at gmail.com>:
>
> a <- 1
> b <- 2
> c <- 3
>
> ls()[-a]  # set minus to all the objects you want to retain
>
> rm(list = ls()[-a]  # will remove all the objects - except a
>
> ls()  # presto

 Only because a=1 and a is the first item in the list! Not because you
are doing '-a'! If a is 0 then nothing gets deleted, and if a isn't
numeric vector then it just fails.

 If you want to do it by name, use match....

Barry



More information about the R-help mailing list