Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove all objects of a given type in R

Tags:

r

How can I use rm to remove all objects of a certain type in R?

I currently have a bunch of functions defined that I'd like to expunge.

I know ls has a pattern option, but this would only help if I was naming all the functions in a pattern (I'm not).

like image 508
MichaelChirico Avatar asked Jun 10 '15 21:06

MichaelChirico


4 Answers

A variation on @Jilber's answer:

rm(list=names(Filter(is.function, mget(ls(all=T)))))
like image 106
BrodieG Avatar answered Oct 06 '22 02:10

BrodieG


You may try ls.str where you can list objects of a certain mode (e.g. integer, list (data frame) or function), or lsf.str (returns functions only):

# some objects to 'look for'
int1 <- 1
char1 <- "a"
list1 <- data.frame(x1, x2)
fun1 <- function() x1 + x2

# ls()
# ls.str()
ls.str(mode = "function")
funs <- as.character(ls.str(mode = "function"))

lsf.str()
funs <- as.character(lsf.str())

# rm(funs)
like image 32
Henrik Avatar answered Oct 06 '22 02:10

Henrik


My solution is basically to use mget to get the class of everything in ls(), then subset ls() according to when class=="function":

rm(list=ls(all=TRUE)[sapply(mget(ls(all=TRUE)), class) == "function"])

@Jilber suggests a cleaner alternative:

rm(list=ls(all=TRUE)[sapply(mget(ls(all=TRUE)), is.function)])

These basic approaches can be expanded to accommodate more complex "genocide" (class-specific purging):

rm(list=ls(all=TRUE)[sapply(mget(ls(all=TRUE)), class) %in% 
    c("function", "numeric")])
rm(list=ls(all=TRUE)[sapply(mget(ls(all=TRUE)),
                            function(x) is.function(x) | is.numeric(x))])

@Jilber's approach also has the advantage that it will catch multi-class objects (most notably, data.tables.

Suppose we wanted to remove all data.frames that are not (also) data.tables:

rm(list=ls(all=TRUE)[sapply(mget(ls(all=TRUE)),
                            function(x) is.data.frame(x) & !is.data.table(x))])
like image 31
MichaelChirico Avatar answered Oct 06 '22 00:10

MichaelChirico


There is an ls.str() function that accepts a mode argument. You can get all the functions in the global environment with:

ls.str( mode="function")  # or in a different environment if properly created

The exists function tests whether it can be found and can be limited to particular mode. This is a potentially destructive effect on a running session

rm( list = ls()[ sapply( ls(), exists, mode="function")] )
# test for errors and effectiveness
any( sapply( ls(), exists, mode="function"))
# [1] FALSE

If you were trying to remove only functions with particular patterns to their names you might select among the character vectors returned by ls() with grepl.

like image 43
IRTFM Avatar answered Oct 06 '22 02:10

IRTFM