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.


Solution 1:

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

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

or

rm(temp1, temp2)

Solution 2:

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

Solution 3:

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)

Solution 4:

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