Reputation: 2141
I'm trying to see if it is possible to have a S3 dispatch inside an R6 class? Or maybe I am missing some feature of R6.
Here is the problem I am trying to resolve:
tmp <- R6::R6Class("tmp",
list(
a = list(x = 1),
b = data.frame(x = 1),
divide = function(x) UseMethod("divide"),
divide.list = function(x) x$x/4,
divide.data.frame = function(x) x$x/2,
test_list = function() self$divide(self$a),
test_df = function() self$divide(self$b)
)
)
tmp2 <- tmp$new()
tmp2$test_df()
#> Error in UseMethod("divide"): no applicable method for 'divide' applied to an object of class "data.frame"
tmp2$test_list()
#> Error in UseMethod("divide"): no applicable method for 'divide' applied to an object of class "list"
Created on 2024-02-19 with reprex v2.1.0
Solutions need not be S3 dispatch, that just captures the essence of what I am trying to do.
Upvotes: 2
Views: 76
Reputation: 20409
The dispatching method simply does not find your S3
implementation inside your R6
class.
It does find it, however, if you define it in the global environment:
tmp <- R6::R6Class("tmp",
list(
a = list(x = 1),
b = data.frame(x = 1),
divide = function(x) UseMethod("divide"),
test_list = function() self$divide(self$a),
test_df = function() self$divide(self$b)
)
)
divide.list <- function(x) x$x/4
divide.data.frame <- function(x) x$x/2
tmp2 <- tmp$new()
tmp2$test_df()
# [1] 0.5
tmp2$test_list()
# [1] 0.25
Upvotes: 0