简体   繁体   中英

Overload as.character/paste for reference classes in R

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"

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM