In loading a few packages to work with some data, I received an error when I tried to use the function select()
from the dplyr
package. I was trying to use a new package (to me), MASS
, so I was easily able to diagnose and get things working properly. This experience made me curious, though, about the optimal way to work in a world of many packages, with functions that conflict with one another.
Consider the following code and error message:
library(dplyr)
library(MASS)
df<-data.frame(Lobsters=c(1,3,4,5,7,1),Llamas=c(7,1,2,5,8,3))
df2<-df%>%
select(Lobsters)
Error in select(.,Lobsters) : unused argument (Lobsters)
While this error makes it clear that select() is giving me the problem, it doesn't necessarily make it clear to me that the problem is that I'm not calling on the select()
function I'm used to.
I know I can call the dplyr
function and get my desired result using:
df2_alt<-df%>%
dplyr::select(Lobsters)
I wonder, though:
Is there a best practice in diagnosing problems with same-named functions, besides the "The following object is masked from" messages when a package is loaded?
Is my method of dplyr::select(
the best way to work around these conflicts?
Ultimately, my current strategy is to load the package that has the select()
function I'll be using more after the package that has the less-frequently-used version.
Here are some things that can be done.
When issuing a library
statement, R will list all conflicts. Pay attention to these! If you need to know the conflicts later enter: conflicts()
.
Use the exclude
argument on library
(R 3.6 and later). e.g. library(MASS, exclude = "select")
. dplyr clobbers base lag
and filter
so you might want to get into the habit of routinely excluding those: library(dplyr, exclude = c("filter", "lag"))
One can still access them using dplyr::lag
, etc.
Use dplyr::select
notation if you find it has been masked.
detach
any packages you are no longer using, e.g. detach("package:MASS")
.
In some cases the masking is benign since the new version it is backwardly compatible and in those cases there is no need to avoid the conflict.
As noted by @LenGreski in the comments the package order will determine the resolution of any conflicts. Each package overrides all prior packages that were loaded before it in the case of conflicts.
There are also a number of packages that address the problem of conflicts including conflicted (mentioned by @MrFlick), modules, import and box which are all on CRAN.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With