我的目标是重载+
运算符,以便在R6 对象上调用方法。这是一个带有 R6 类对象的玩具示例,该类对象本身aclass
具有add_function(foo)
存储某些任意函数的方法。
我想用ggplot2 的 +.gg 或 +(e1,e2)的样式替换对add_function(foo)
by的调用。我检查了ggplot2 github 代码,但无法弄清楚。+ foo
这是一个 R6 对象,我们可以在其中添加任意函数
library(R6)
# The class (called aclass) looks like so:
Aclass <- R6Class("aclass",
public = list(
fun = NULL,
x = NULL,
initialize = function(x) {
self$x <- x
return(invisible(self))
},
# this is the function adding part
add_fun = function(fun) {
self$fun <- substitute(fun)
},
# and here we execute the functions
do_fun = function() {
return(eval(self$fun)(self$x))
}))
# Say, we want to add this function to an aclass object
foo <- function(x) mean(x, na.rm=TRUE)
这有效
# Instantiate class
my_class <- Aclass$new(c(0,1,NA))
# Add the function
my_class$add_fun(function(x) mean(x, na.rm=TRUE))
# my_class$add_fun(foo) # this also works
# Execute the function - beautiful - returns 0.5
my_class$do_fun()
这失败了
我的目标是做与上面相同的事情,即将 foo 添加到对象中,但现在通过重载 + 运算符以更好的方式完成工作
# Let's try to overload the + operator
`+.aclass` <- function(e1, e2) {
return(e1$add_fun(e2))
}
# option 1
my_class <- Aclass$new(c(0,1,NA)) + foo
# fails
# Looking at my class we get
my_class
# > my_class
# e2
# option 2 <--- this is my end goal
my_class <- Aclass$new(c(0,1,NA)) + mean(x, na.rm=TRUE)
# also fails because then R tries to execute the function
# > Error in mean(x, na.rm = TRUE) : Object 'x' not found
# Note: in this case, the custom +.aclass is not even called,
# but R calls the normal + method I think
我不确定如何解决这个问题,或者它是否真的可能......
谢谢你的帮助!