我经常创建临时对象,其名称以' tp _'并使用用户定义的功能。为了保持干净的工作空间,我想创建一个在保留用户定义的函数的同时删除临时文件的函数。
到目前为止,我的代码是:
rm(list = setdiff(ls(), lsf.str())) # Removes all objects except functions
rm(list = ls(, pattern = "tp_")) # Removes all objects whose name contain 'tp_'
我想:
substr(ls(), 1, 3)
,但不知何故无法将其整合到我的功能中。一些R对象:
tp_A = 1
myfun = function(x){sum(x)}
atp_b = 3
该功能应仅从工作区中删除tp_A
。
答案 0 :(得分:9)
pattern参数使用正则表达式。您可以使用插入符号^
来匹配字符串的开头:
rm(list=ls(pattern="^tp_"))
rm(list=setdiff(ls(pattern = "^tp_"), lsf.str()))
但是,还有其他模式来管理临时项目/保持干净的工作空间而不是名称前缀。
例如,考虑一下
temp<-new.env()
temp$x <- 1
temp$y <- 2
with(temp,x+y)
#> 3
rm(temp)
另一种可能性是attach(NULL,name="temp")
assign
。