My aim is to overload the +
operator in order to call a method on an R6 object. Here is a toy example with an R6 object of class aclass
that has a method add_function(foo)
to store some arbitrary function in itself.
I want to substitute the call to add_function(foo)
by + foo
in the style of ggplot2's +.gg or +(e1,e2). I checked the ggplot2 github code but could not figure this out.
Here is an R6 object to which we can add arbitrary functions
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)
This works
# 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()
This fails
My goal is to do the same as above, i.e. adding foo to the object, but now by overloading the + operator to do the job in a nicer way
# 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
I am not sure how to solve this or if it is actually possible...
Thanks for any help!