使用rm()删除多个对象


84

一堆中间文件(称为temp1,temp2等)阻塞了我的内存。是否有可能从内存中删除他们不这样做rm(temp1)rm(temp2)一次一个?我试过了rm(list(temp1, temp2, etc.)),但这似乎不起作用。

Answers:


123

使列表成为字符向量(而不是名称的向量)

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

要么

rm(temp1, temp2)

3
要删除内存中的所有内容,您可以说:rm(list = ls())
2012年

5
@Sam,rm(list = ls(all = TRUE))如果您想确保获得所有内容。
戴森

1
可以用%>%吗?例如list(...) %>% rm(list = .)
Jiaxiang

请您说明一下它的优点是list什么?在我看来,在第二个选项中键入所有变量名称而不只是TAB自动完成功能不必要地复杂。
laviex19年

112

另一种解决方案rm(list=ls(pattern="temp")),删除所有与模式匹配的对象。


乔什·保尔森(Josh Paulson)在这里描述(我不知道是ls(...)做什么的,但现在我想它就像是Unix bash函数ls吗?)-糟糕,乔什·保尔森(Josh Paulson)使用了@Sam描述的特定变种To remove everything in the memory, you can say: rm(list = ls())
Red Pea

这可以正常工作,但可能有一个小错误。如果有一个名称为'ABCtemp'的对象,它也会被删除。我怎样才能删除那些以'temp'开头并保留'ABCtemp'的对象?
user3768495'1

8
您可以简单地向您的模式添加更多条件。对于您的示例,pattern="^temp"将仅捕获以“ temp”开头的变量,而不捕获变量ABCtemp
艾伦(Alan)

1
另一种可能性是通过@BrodieG这里给出的答案stackoverflow.com/questions/21677923/...
绿色DIOD

3

或使用正则表达式

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

3

您可以尝试的另一种变化是(扩展@mnel的答案),如果您有很多temp'x'。

这里的“ n”可能是存在的临时变量的数量

rm(list = c(paste("temp",c(1:n),sep="")))
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.