在R中添加对象(如ggplot图层)

Gre*_*reg 5 r ggplot2

我正在做OOP R并且想知道如何制作它以便+可以用来将自定义对象添加到一起.我发现的最常见的例子是ggplot2将wom添加到一起.

我仔细阅读了ggplot2源代码并发现了这一点

https://github.com/hadley/ggplot2/blob/master/R/plot-construction.r

它看起来似乎"%+%"正在被使用,但目前尚不清楚它最终如何转化为普通+运营商.

Jos*_*ien 5

您只需要为泛型函数定义一个方法+.(在您的问题中的链接,该方法"+.gg"旨在由类的参数调度"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
Run Code Online (Sandbox Code Playgroud)