Delete all variables except functions

I loaded different types of objects into the R-console. I can delete them all using

rm(list=ls()) 

or remove only functions (but not variables) using

 rm(list=lsf.str()) 

My question is: is there a way to remove all variables except functions

+86
caching r
Nov 29 '11 at 4:13
source share
4 answers

Here is a single line that deletes all objects except functions:

 rm(list = setdiff(ls(), lsf.str())) 

It uses setdiff to find a subset of objects in the global environment (as returned by ls() ) that do not have function mode (as returned by lsf.str() )

+98
Nov 29 '11 at 4:27
source share

The setdiff response setdiff is good. I just thought I'd post this related function that I wrote some time ago. Its usefulness depends on 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])) } 
+7
Nov 29 '11 at 12:48
source share

Here's a pretty handy feature that I picked up somewhere and got a little better. It may be nice to store in a directory.

 list.objects <- function(env = .GlobalEnv) { if(!is.environment(env)){ env <- deparse(substitute(env)) stop(sprintf('"%s" must be an environment', env)) } obj.type <- function(x) class(get(x, envir = env)) foo <- sapply(ls(envir = env), obj.type) object.name <- names(foo) names(foo) <- seq(length(foo)) dd <- data.frame(CLASS = foo, OBJECT = object.name, stringsAsFactors = FALSE) dd[order(dd$CLASS),] } > x <- 1:5 > d <- data.frame(x) > list.objects() # CLASS OBJECT # 1 data.frame d # 2 function list.objects # 3 integer x > list.objects(env = x) # Error in list.objects(env = x) : "x" must be an environment 
0
Jun 23 '14 at 4:55
source share

You can use the following command to clear ALL variables. Be careful because you cannot return your variables.

 rm(list=ls(all=TRUE)) 
0
Oct 25 '17 at 20:47 on
source share



All Articles