Overloading + operator and incompatibility exception
I tried to overload the + operator and ran into incompatibility issues. Even though the + function is a generic S3 function, it seems to treat both arguments (similar to multiple dispatch), not just the left argument, like other generic S3 functions (see "Ops" groups at http: // www .inside-r.org / r-doc / base / summary ). So, if two different + functions are defined for the arguments, R will issue a warning and fall back to + for the two numeric values.
Here's an example:
myType1 <- function(obj) {
structure(obj, class = "myType1")
} # function myType1
`+.myType1` <- function(obj1, obj2) {
return(obj1)
} # function +.myType1
myType2 <- function(obj) {
structure(obj, class = "myType2")
} # function myType2
`+.myType2` <- function(obj1, obj2) {
return(obj2)
} # function +.myType2
myType1("A") + 1 # this works, use defined types seem to have precedence
myType1("A") + myType2(1) # this doesn't
Is there a way to get around this problem? I know S4 methods support multiple dispatch. Would using S4 help me avoid this problem even if an S3 + method is defined for one of the arguments?
Thank you so much in advance.
Regards, Junghoon Lee
source to share
No one has answered this question yet
Check out similar questions: