Reputation: 954
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_'
I want to:
substr(ls(), 1, 3)
but somehow cannot integrate it to my function.Some R objects:
tp_A = 1
myfun = function(x){sum(x)}
atp_b = 3
The function should remove only tp_A
from the workspace.
Upvotes: 25
Views: 15932
Reputation: 26446
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.
Consider, for example,
temp<-new.env()
temp$x <- 1
temp$y <- 2
with(temp,x+y)
#> 3
rm(temp)
Another possibility is attach(NULL,name="temp")
with assign
.
Upvotes: 33