nikUoM
nikUoM

Reputation: 679

rm() and detach() in function - not working

I have a function, which is supposed to do the following:

Here's an example:

removeReload <- function(old, new){
rm(old)
detach("package:anypackage")
library(anypackage)
new <- new
}

However, this function does not remove old from the workspace. I also tried this function as old <- NULL, but again to no avail.

Any ideas as to why this is the case, and how to get old to be removed?

Thanks!

Upvotes: 0

Views: 226

Answers (1)

Gregor Thomas
Gregor Thomas

Reputation: 146224

rm comes with an envir argument to specify the environment to remove objects from. The default is the environment in which rm was called. Normally, if you use rm(blah), the calling environment is the environment you're working in, but if you put rm inside a function, the calling environment is the function environment. You can use rm(old, envir = .GlobalEnv)

Beware programming with this function - it may lead to unintended consequences if you put it inside yet another function.

Example:

> foo = function() {
+   rm(x, envir = .GlobalEnv)
+ }
> x = 1
> foo()
> x

There are more details in at the help page, ?rm, and that page links to ?environment for even more detail.


Similarly, the new <- new as the last line of your function is not doing assignment in the global environment. Normal practice would be to have your function return(new) and do the assignment as it is called, something like new <- removeUnload(old, new). But it's hard to make a "good practice" recommendation from the pseudocode you provide, since you pass in new as an input... it isn't clear whether your function arguments are objects or character strings of object names.

Upvotes: 2

Related Questions