Mus
Mus

Reputation: 7530

How can I check if an object exists in the global environment and then remove it from within a function?

There are some similar questions to this, but the answers provided are tailored to those questions in which the examples given are much more complex than in my scenario.

I have a simple function that creates an object in the global environment (global_obj).

Let's say:

my_function <- function(x){
    global_obj <<- x
}

How can I set the function to check if global_obj exists in the global environment and, if so, to then remove it before proceeding?

I have tried something like this:

if(exists("global_obj")){ rm("global_obj"); print("global_obj removed") }

And:

if(exists("global_obj")){ rm(global_obj); print("global_obj removed") }

But receive the error messages:

[1] "global_obj removed"
Warning message:
In rm("global_obj") : object 'global_obj' not found

And:

[1] "global_obj removed"
Warning message:
In rm(global_obj) : object 'global_obj' not found

Despite the "success message", the error message implies that global_obj was never removed because it couldn't be found.

Some answers suggested pointing rm() to the global environment, which makes sense, but this still results in the same outcome.

Finally, I know that global_obj will be replaced each time I run my_function(), but there is an important reason why I want to remove it each time: it is to prevent any instances where the function may have completed incorrectly but without any warning.

As such, this would lead me to believe that the global_obj that exists in my global environment is the one from the most recent my_function() call when in fact the global_obj that I see could have existed from a previous execution of it.

I want to be certain that the global_obj that I see in my global environment is the most recent one. If the function fails, I expect my environment to be empty.

Upvotes: 2

Views: 1998

Answers (1)

Mus
Mus

Reputation: 7530

I figured out what the problem was - I needed to point rm() at the global environment:

if(exists("global_obj")) rm("global_obj", envir = globalenv())

Upvotes: 4

Related Questions