Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Write a function to remove object if it exists

Tags:

function

r

I am trying to write a function that removes an object if it exists. The reason is that I want to get rid of the log-message Error: object 'arg' not found. I tried the following:

ifrm <- function(arg)
{
   if(exists(as.character(substitute(arg)))){rm(arg)}
}

Unfortunately this does not remove the object if it exists

> ifrm <- function(arg)
+ {
+    if(exists(as.character(substitute(arg)))){rm(arg)}
+ }
> a <- 2
> ifrm(a)
> a
[1] 2

Any hints what I do wrong here?

Best Albrecht

like image 459
Tungurahua Avatar asked Aug 24 '11 08:08

Tungurahua


2 Answers

A general idiom to grab what the user supplied as an argument to a function is deparse(substitute(foo)). This function is similar to that of @Ian Ross but employing this standard idiom:

ifrm <- function(obj, env = globalenv()) {
    obj <- deparse(substitute(obj))
    if(exists(obj, envir = env)) {
        rm(list = obj, envir = env)
    }
}

where I assume you only ever want to remove objects from the global environment, hence the default, but you can supply an environment via env. And here it is in action:

> a <- 1:10
> ls()
[1] "a"    "ifrm"
> ifrm(a)
> ls()
[1] "ifrm"
> ifrm(a)
> ls()
[1] "ifrm"
like image 57
Gavin Simpson Avatar answered Oct 13 '22 10:10

Gavin Simpson


Try this

 a=1; b=3; y=4; ls() 
 rm( list = Filter( exists, c("a", "b", "x", "y") ) )
 ls()
like image 41
baptiste Avatar answered Oct 13 '22 10:10

baptiste