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

Nikhil Kaza nikhil.list at gmail.com
Tue Aug 24 15:04:45 CEST 2010


or use

#not checked
rm(setdiff(ls(),c("a", "b"))

On Aug 24, 2010, at 4:55 AM, Barry Rowlingson wrote:

> 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
>
> ______________________________________________
> R-help at r-project.org mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.



More information about the R-help mailing list