使用 rm()删除多个对象

我的内存被一堆中间文件(称为 temp1temp2,等等)堵塞了,我想知道是否有可能在不重复 rm调用(即 rm(temp1)rm(temp2))的情况下将它们从内存中删除?

我试过 rm(list(temp1, temp2, etc.))但好像没用。

139033 次浏览

Make the list a character vector (not a vector of names)

rm(list = c('temp1','temp2'))

or

rm(temp1, temp2)

Or using regular expressions

"rmlike" <- function(...) {
names <- sapply(
match.call(expand.dots = FALSE)$..., as.character)
names = paste(names,collapse="|")
Vars <- ls(1)
r <- Vars[grep(paste("^(",names,").*",sep=""),Vars)]
rm(list=r,pos=1)
}


rmlike(temp)

An other solution rm(list=ls(pattern="temp")), remove all objects matching the pattern.

Another variation you can try is (expanding @mnel's answer) if you have many temp'x'.

Here, "n" could be the number of temp variables present:

rm(list = c(paste("temp",c(1:n),sep="")))