Reputation: 41
I have built a simple Config reference class in R
and I am trying to adjust it so that 'pasting' a list including a Config object will work (something similar to overloading >> operator in C++
).
Code snippet:
Config <- setReferenceClass ("Config" , fields = c ("parameters" )
Config$methods (initialize = function (parameters) { .self$parameters = parameters })
setMethod ("as.character", "Config", function (conf) { return (paste (conf$parameters, sep="_", collapse = "_")})
foo = Config$new (list (gender="male", age = c(40,50)))
as.character (foo)
paste (list("a" , foo, 12), sep ="_" , collapse = "_")
R seems to ignore my override when in a list. I guess I'm missing something in syntax - but couldn't find relevant enough examples to get this to work.
I was hoping to get:
male_40_50
a_male_40_50_12
Instead I get:
[1] "male_40_50"
and
[1] "a_< S4 object of class \"Config\">_12"
Upvotes: 0
Views: 69
Reputation: 163
Your example with setMethod does not work for reference classes in R 4.1. But you can use the old method for S3 classes to define as.character() like this:
Config <- setRefClass ("Config" , fields = c ("parameters" ))
Config$methods(
initialize = function (parameters) { .self$parameters = parameters },
)
as.character.Config <- function(obj){
paste(obj$parameters, sep="_", collapse = "_")
}
foo = Config$new (list (gender="male", age = c(40,50)))
as.character(foo)
Unfortunately, this does also not work in your list()-case.
Upvotes: 0