Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dealing with conflicting namespaces in R (same function names in different packages): reset precedence of a package namespace

Tags:

package

r

The name conflicts between namespaces from different packages in R can be dangerous, and the use of package::function is unfortunately not generalized in R...

Isn't there a function that can reset the precedence of a package namespace over all the others currently loaded? Surely we can detach and then reload the package, but isn't there any other, more practical (one-command) way?

Because I often end up with many packages and name conflicts in my R sessions, I use the following function to do that:

set_precedence <- function(pckg) {
  pckg <- deparse(substitute(pckg))
  detach(paste("package", pckg, sep = ":"), unload=TRUE, character.only=TRUE)
  library(pckg, character.only=TRUE)
}
# Example
set_precedence(dplyr)

No built-in way to achieve this in a single command? Or a way that doesn't imply detaching and reloading the package, in case it is heavy to load, and working directly on namespaces?

like image 344
ztl Avatar asked Mar 31 '16 09:03

ztl


1 Answers

Here's a way that do not reload the package and work directly on the environments/namespaces. Just replace your library() call with attachNamespace():

set_precedence <- function(pkg) {
  detach(paste0("package:", pkg), character.only = TRUE)
  attachNamespace(pkg)
}

set_precedence('utils')
# now utils is in pos #2 in `search()`
like image 123
Karl Forner Avatar answered Nov 17 '22 20:11

Karl Forner