[R] Removing objects and clearing memory
Rolf Turner
rolf.turner at xtra.co.nz
Wed Apr 13 00:45:37 CEST 2011
On 13/04/11 09:49, Denis Kazakiewicz wrote:
> On 13.04.2011 00:39, Jim Silverton wrote:
>> How do I remove all objects except one in R?
>>
> rm(list=ls()) #will remove ALL objects
But he wanted to remove all objects ***except one***!!! So what's the
point of this answer?
I can't see any way except a rather round-about kludge to do what the
OP wants.
Create a function:
rmabo <- function(x) {
# Remove all but one.
fff <- tempfile()
save(list=deparse(substitute(x)),file=fff)
rm(list=ls(pos=1),pos=1)
load(fff,envir=.GlobalEnv)
unlink(fff)
}
Save this function (otherwise it will get removed when you remove
all objects except one, and rmabo is not the one, and will be lost):
save(rmabo,file=".rmabo.rda")
Whenever you want to remove all objects except one, attach the
data base in which you have saved "rmabo". (You only need to do
the attaching once per session; if you like you could put the attach
command in your .Rprofile.)
attach(".rmabo.rda")
Then to remove all objects except "melvin" execute rmabo(melvin).
E.g.:
rm(list=ls)
ls()
character(0)
melvin <- clyde <- irving <- fred <- 42
ls()
[1] "clyde" "fred" "irving" "melvin"
rmabo(melvin)
ls()
[1] "melvin"
This seems to work. Anyone have any cleverer ideas to accomplish the
stated objective?
cheers,
Rolf Turner
More information about the R-help
mailing list