[r] Remove multiple objects with rm()

My memory is getting clogged by a bunch of intermediate files (call them temp1, temp2, etc.). and I would like to know if it is possible to remove them from memory without doing repeated rm calls (i.e. rm(temp1), rm(temp2))?

I tried rm(list(temp1, temp2, etc.)), but that doesn't seem to work.

This question is related to r

The answer is


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="")))

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)