1

I've seen some packages that defines new classes and binary operators like + or - still work. There must be a way to define how + operates according to the class of the two arguments, in a way like defining

plot.myclass = function(x) something

changes what plot() does if the argument is of class myclass.

How can I change what a built-in binary operator does? Do they work exactly like S3 methods?

As an example, let's say I want to have an addition operator for character objects, so that

"abc" + "def"

returns "abcdef", how to specify that I want + to return paste(arg1,arg2) when the arguments are character objects.

VFreguglia
  • 2,129
  • 4
  • 14
  • 35
  • You can use infix function sth like, sorry not tested but should work, ` ``%+%`` <- function(x, y)paste0(x,y)`, the left hand side statement should be wrapped in back ticks, its a back tick , not sure it rendered properly. You can use it like 'a' %+% 'b' – PKumar Aug 01 '18 at 01:28
  • @PKumar if this works, I think it would break regular addition, as `1+1` would return `"11"`(character). I need it to change only for a certain type of arguments. – VFreguglia Aug 01 '18 at 01:33
  • Are you talking about function or operator overloading – PKumar Aug 01 '18 at 01:34
  • 2
    @李哲源 It's because `+` uses S4 not S3 dispatch, but see Lytze's answer at the dupe for a clever work-around. – Gregor Thomas Aug 01 '18 at 02:04

0 Answers0