使用 R 删除名称以模式开头的工作区对象 [英] Removing workspace objects whose name start by a pattern using R
问题描述
我经常创建名称以tp_"开头的临时对象,并使用用户定义的函数.为了保持工作区干净,我想创建一个删除临时文件的函数,同时保留用户定义的函数.
I often create temporary objects whose names start by 'tp_' and use user-defined function. In order to keep a clean workspace, I would like to create a function that removes temporary files while keeping user-defined functions.
到目前为止,我的代码是:
So far, my code is:
rm(list = setdiff(ls(), lsf.str())) # Removes all objects except functions
rm(list = ls(, pattern = "tp_")) # Removes all objects whose name contain 'tp_'
我想:
- 改进第二个函数,以便删除名称开始 'tp_' 的对象(到目前为止,它删除了名称包含 'tp_' 的对象).我试过
substr(ls(), 1, 3)
但不知何故无法将它集成到我的函数中. - 将这两个功能合二为一.
- Improve the second function so that is removes objects whose name start by 'tp_' (so far, it removes objects whose name contains 'tp_'). I've tried
substr(ls(), 1, 3)
but somehow cannot integrate it to my function. - Combine these two functions into one.
一些 R 对象:
tp_A = 1
myfun = function(x){sum(x)}
atp_b = 3
该函数应仅从工作区中删除 tp_A
.
The function should remove only tp_A
from the workspace.
推荐答案
模式参数使用正则表达式.您可以使用插入符号 ^
来匹配字符串的开头:
The pattern argument uses regular expressions. You can use a caret ^
to match the beginning of the string:
rm(list=ls(pattern="^tp_"))
rm(list=setdiff(ls(pattern = "^tp_"), lsf.str()))
但是,除了名称前缀之外,还有其他模式可用于管理临时项目/保持干净的工作区.
However, there are other patterns for managing temporary items / keeping clean workspaces than name prefixes.
考虑,例如,
temp<-new.env()
temp$x <- 1
temp$y <- 2
with(temp,x+y)
#> 3
rm(temp)
另一种可能是 attach(NULL,name="temp")
和 assign
.
Another possibility is attach(NULL,name="temp")
with assign
.
这篇关于使用 R 删除名称以模式开头的工作区对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!