Write a function to delete an object, if it exists

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

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

Unfortunately, this does not delete 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 of what I'm doing wrong here?

Best Albrecht

+6
source share
4 answers

The general idiom for capturing what the user has set as an argument to a function is deparse(substitute(foo)) . This function is similar to the @Ian Ross function, but using 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 that you only want to remove objects from the global environment, therefore by default, but you can provide the environment through env . And here he is in action:

 > a <- 1:10 > ls() [1] "a" "ifrm" > ifrm(a) > ls() [1] "ifrm" > ifrm(a) > ls() [1] "ifrm" 
+8
source

Keep it simple. Just pass the name of the object to your function as a character string, instead of trying to get the name from the actual object.

 ifrm <- function(x, env = globalenv()) { if(exists(x, envir = env)) { rm(list = x, envir = env) } } 
+3
source

try it

  a=1; b=3; y=4; ls() rm( list = Filter( exists, c("a", "b", "x", "y") ) ) ls() 
+2
source

This is disgusting, but it seems to work:

 ifrm <- function(arg) { if (exists(as.character(substitute(arg)))) { rm(list=as.character(substitute(arg)), envir=sys.frame()) } } 

You might want to specify the environment in different ways if you do not remove the names from the top-level environment.

+1
source

Source: https://habr.com/ru/post/895728/


All Articles