Search code examples
robjectworkspace

Removing workspace objects whose name start by a pattern using R


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:

  1. 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.
  2. Combine these two functions into one.

Some R objects:

tp_A = 1
myfun = function(x){sum(x)}
atp_b = 3

The function should remove only tp_A from the workspace.


Solution

  • 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.