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.table
s.
Suppose we wanted to remove all data.frame
s that are not (also) data.table
s:
rm(list=ls(all=TRUE)[sapply(mget(ls(all=TRUE)),
function(x) is.data.frame(x) & !is.data.table(x))])