8

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?

ztl
  • 2,512
  • 1
  • 26
  • 40

3 Answers3

1

I would suggest taking a look at the conflicted package.

te time
  • 485
  • 3
  • 9
1

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()`
Karl Forner
  • 4,175
  • 25
  • 32
0

Prefix the package name with a double colon: <package>::<function>()

For instance:

ggplot2::ggplot(data=data, ggplot2::aes(x=x)) +
    ggplot2::geom_histogram()

More typing, but I feel so much less anxious using R now that I have found this.

Kaleb Coberly
  • 420
  • 1
  • 4
  • 19