Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding objects together in R (like ggplot layers)

Tags:

r

ggplot2

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.

like image 765
Greg Avatar asked May 29 '13 02:05

Greg


1 Answers

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
like image 151
Josh O'Brien Avatar answered Sep 20 '22 22:09

Josh O'Brien