简体   繁体   English

在 R 中为参考类重载 as.character/paste

[英]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++ ).我在 R 中构建了一个简单的配置引用R并且我正在尝试调整它以便“粘贴”包含配置 object 的列表将起作用(类似于重载 >> 运算符在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. R 在列表中时似乎忽略了我的覆盖。 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.您使用 setMethod 的示例不适用于 R 4.1 中的参考类。 But you can use the old method for S3 classes to define as.character() like this:但是您可以使用 S3 类的旧方法来定义 as.character() ,如下所示:

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.不幸的是,这在您的 list() 案例中也不起作用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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