I'm doing OOP R and was wondering how to make it so the +
can be used to add custom objects together. The most common example of this I've found is in ggplot2
w/ adding geoms together.
I read through the ggplot2
source code and found this
https://github.com/hadley/ggplot2/blob/master/R/plot-construction.r
It looks like "%+%"
is being used, but it's not clear how that eventually translates into the plain +
operator.
You just need to define a method for the generic function +
. (At the link in your question, that method is "+.gg"
, designed to be dispatched by arguments of class "gg"
). :
## Example data of a couple different classes
dd <- mtcars[1, 1:4]
mm <- as.matrix(dd)
## Define method to be dispatched when one of its arguments has class data.frame
`+.data.frame` <- function(x,y) rbind(x,y)
## Any of the following three calls will dispatch the method
dd + dd
# mpg cyl disp hp
# Mazda RX4 21 6 160 110
# Mazda RX41 21 6 160 110
dd + mm
# mpg cyl disp hp
# Mazda RX4 21 6 160 110
# Mazda RX41 21 6 160 110
mm + dd
# mpg cyl disp hp
# Mazda RX4 21 6 160 110
# Mazda RX41 21 6 160 110
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