In R, whenever two packages define the same function, it is easy to specify which package to use with pkg::foo
. But how do you when the conflicted function is an infix operator, i.e. defined using %%
?
As an example, both ggplot2
and crayon
define %+%
. Is there a way I can use by default ggplot2
's %+%
, but in a given line, using crayon
's %+%
? Just doing crayon::`%+%`
is calling the right function (note the backticks), but does not work as infix operator anymore!? I can do crayon::`%+%`(a, b)
, it works, but it is not the function as an operator!
Code:
> library(crayon)
> "foo" %+% "bar"
[1] "foobar"
> crayon::`%+%`("foo" ,"bar")
[1] "foobar"
> "foo" crayon::`%+%` "bar"
Error: unexpected symbol in ""foo" crayon"
Adding from @MrFlick's comment:
Unfortunately you can't use namespaces with infix operators in R; the parser just won't recognize that syntax. You need to create an alias as suggested in the answer below. Or create your own version of the operator that does dispatching based on the classes you expect to see.
Just an idea but: how about redefining the infix function's binding. Suppose the one from ggplot2
is the one you are going to use most often in your code:
library(ggplot2)
`%+c%` <- crayon::`%+%`
This way you are correctly namespacing the ggplot2
library and you just use a different binding for the crayon
one.