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))
Share:
127,039
RockScience
Author by

RockScience

Updated on April 09, 2020

Comments

  • RockScience
    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
    Josh O'Brien over 12 years
    If 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
    Josh O'Brien over 12 years
    Thanks for posting that. It makes for an interesting comparison with the code for ls.str() which, however, tests the mode rather than the typeof of objects. (On a side note, I'll be darned if I can figure the difference between those two from their documentation).
  • RockScience
    RockScience over 12 years
    Thanks a lot for this answer. May I know what is a period?
  • RockScience
    RockScience over 12 years
    I always use class instead of typeof
  • Josh O'Brien
    Josh O'Brien over 12 years
    Sure. 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
    RockScience over 12 years
    great, thank you. I already noticed that .j was not affected by ls() but could explain that.
  • RockScience
    RockScience over 6 years
    Good to know but that's not the not the question
  • lwileczek
    lwileczek over 6 years
    I guess I should have left that as a comment since it was more of an FYI. Sorry.
  • DiveIntoML
    DiveIntoML over 4 years
    Please add more information about "current environment", e.g. whether this is shell or certain programming language