Remove multiple objects with rm()

R

R Problem Overview


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.

R Solutions


Solution 1 - R

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

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

or

rm(temp1, temp2)

Solution 2 - R

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

Solution 3 - R

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 - R

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionuser702432View Question on Stackoverflow
Solution 1 - RmnelView Answer on Stackoverflow
Solution 2 - RAlanView Answer on Stackoverflow
Solution 3 - RDieter MenneView Answer on Stackoverflow
Solution 4 - RDeepeshView Answer on Stackoverflow