remove all variables except functions
127,039
Solution 1
Here's a one-liner that removes all objects except for functions:
rm(list = setdiff(ls(), lsf.str()))
It uses setdiff
to find the subset of objects in the global environment (as returned by ls()
) that don't have mode function
(as returned by lsf.str()
)
Solution 2
The posted setdiff
answer is nice. I just thought I'd post this related function I wrote a while back. Its usefulness is up to the reader :-).
lstype<-function(type='closure'){
inlist<-ls(.GlobalEnv)
if (type=='function') type <-'closure'
typelist<-sapply(sapply(inlist,get),typeof)
return(names(typelist[typelist==type]))
}
Solution 3
You can use the following command to clear out ALL variables. Be careful because it you cannot get your variables back.
rm(list=ls(all=TRUE))
Author by
RockScience
Updated on April 09, 2020Comments
-
RockScience about 4 years
I have loaded in a R console different type of objects. I can remove them all using
rm(list=ls())
or remove only the functions (but not the variables) using
rm(list=lsf.str())
My question is: is there a way to remove all variables except the functions
-
Josh O'Brien over 12 yearsIf you also want to remove objects whose names start with a period, use this instead:
rm(list=setdiff(ls(all.names=TRUE), lsf.str(all.names=TRUE)))
-
Josh O'Brien over 12 yearsThanks for posting that. It makes for an interesting comparison with the code for
ls.str()
which, however, tests themode
rather than thetypeof
of objects. (On a side note, I'll be darned if I can figure the difference between those two from their documentation). -
RockScience over 12 yearsThanks a lot for this answer. May I know what is a period?
-
RockScience over 12 yearsI always use class instead of typeof
-
Josh O'Brien over 12 yearsSure. A period (in American English) is another name for a dot, like this:
.
To see what I'm talking about, try.j <- 5; ls(); ls(all.names=TRUE)
-
RockScience over 12 yearsgreat, thank you. I already noticed that .j was not affected by ls() but could explain that.
-
RockScience over 6 yearsGood to know but that's not the not the question
-
lwileczek over 6 yearsI guess I should have left that as a comment since it was more of an FYI. Sorry.
-
DiveIntoML over 4 yearsPlease add more information about "current environment", e.g. whether this is shell or certain programming language