Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 335
goclem Avatar asked Sep 01 '15 15:09

goclem


People also ask

How do I remove an object from a workspace in R?

Actually, there are two different functions that can be used for clearing specific data objects from the R workspace: rm() and remove(). However, these two functions are exactly the same. You can use the function you prefer. The previous R code also clears the data object x from the R workspace.

What is the function name that removes objects from the R workspace?

rm() function in R Language is used to delete objects from the memory. It can be used with ls() function to delete all objects. remove() function is also similar to rm() function.

How do you unassign an object in R?

Description. remove and rm can be used to remove objects. These can be specified successively as character strings, or in the character vector list , or through a combination of both. All objects thus specified will be removed.

How do you remove all objects except one in R?

I think another option is to open workspace in RStudio and then change list to grid at the top right of the environment(image below). Then tick the objects you want to clear and finally click on clear. Likewise, click the Name box, which selects all the files, and then deselect all the files you want to keep.


1 Answers

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.

like image 53
A. Webb Avatar answered Sep 29 '22 00:09

A. Webb