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).
A variation on @Jilber's answer:
rm(list=names(Filter(is.function, mget(ls(all=T)))))
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)
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))])
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With