使用R删除名称以模式开头的工作空间对象

goc*_*lem 6 workspace r object

我经常创建临时对象,其名称以'tp_'开头并使用用户定义的函数.为了保持干净的工作空间,我想创建一个在保留用户定义的函数的同时删除临时文件的函数.

到目前为止,我的代码是:

rm(list = setdiff(ls(), lsf.str())) # Removes all objects except functions
rm(list = ls(, pattern = "tp_")) # Removes all objects whose name contain 'tp_'
Run Code Online (Sandbox Code Playgroud)

我想要:

  1. 改进第二个函数,以便删除名称以'tp_' 开头的对象(到目前为止,它删除名称中包含 'tp_'的对象).我已经尝试substr(ls(), 1, 3)但不知何故无法将其集成到我的功能中.
  2. 将这两个功能合二为一.

一些R对象:

tp_A = 1
myfun = function(x){sum(x)}
atp_b = 3
Run Code Online (Sandbox Code Playgroud)

该功能应仅从tp_A工作区中删除.

A. *_*ebb 13

pattern参数使用正则表达式.您可以使用插入符号^来匹配字符串的开头:

rm(list=ls(pattern="^tp_"))
rm(list=setdiff(ls(pattern = "^tp_"), lsf.str()))
Run Code Online (Sandbox Code Playgroud)

但是,还有其他模式用于管理临时项目/保持干净的工作空间而不是名称前缀.

例如,考虑一下

temp<-new.env()
temp$x <- 1
temp$y <- 2
with(temp,x+y)
#> 3
rm(temp)
Run Code Online (Sandbox Code Playgroud)

另一种可能性是attach(NULL,name="temp")assign.