104

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.

AndrewGB
  • 16,126
  • 5
  • 18
  • 49
user702432
  • 11,898
  • 21
  • 55
  • 70

4 Answers4

154

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

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

or

rm(temp1, temp2)
mnel
  • 113,303
  • 27
  • 265
  • 254
  • 4
    To remove everything in the memory, you can say: rm(list = ls()) – Sam Jul 24 '12 at 06:04
  • 7
    @Sam `rm(list = ls(all = TRUE))` if you want to be sure to get everything. – Dason Aug 22 '15 at 18:05
  • 1
    Does it work in `%>%`? Such as `list(...) %>% rm(list = .)` – Jiaxiang Oct 12 '18 at 03:05
  • 1
    Would you please explain what it the advantage of `list`? Seems to me unnecessarily complicated to type all the variable names instead of just TAB autocomplete in the second option. – laviex Nov 14 '19 at 19:48
138

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

Alan
  • 3,153
  • 2
  • 15
  • 11
  • Described [here](https://support.rstudio.com/hc/en-us/articles/200711843-Working-Directories-and-Workspaces) by Josh Paulson (I didn't know what `ls(...)` did, but now I guess it's like the Unix bash function ls?) -- whoops, Josh Paulson used a specific variety described by @Sam `To remove everything in the memory, you can say: rm(list = ls()) ` – Nate Anderson Sep 06 '15 at 22:49
  • This works fine but might have a small bug.If there is a object with name 'ABCtemp', it will also be removed. How can I just remove those objects that start with 'temp' and keep the 'ABCtemp'? – user3768495 Jan 11 '16 at 18:45
  • 14
    You can simply add more criterion to your pattern. For your example, `pattern="^temp"` will catch only variable beginning by "temp", so not the variable `ABCtemp`. – Alan Mar 22 '16 at 14:54
  • 2
    Another possibility is the answer given by @BrodieG here https://stackoverflow.com/questions/21677923/how-to-remove-selected-r-variables-without-having-to-type-their-names – green diod Dec 30 '16 at 21:39
5

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)
Dieter Menne
  • 10,076
  • 44
  • 67
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="")))
AndrewGB
  • 16,126
  • 5
  • 18
  • 49
Deepesh
  • 820
  • 1
  • 14
  • 32