繁体   English   中英

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

[英]Overload as.character/paste for reference classes in R

我在 R 中构建了一个简单的配置引用R并且我正在尝试调整它以便“粘贴”包含配置 object 的列表将起作用(类似于重载 >> 运算符在C++中)。

代码片段:

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 在列表中时似乎忽略了我的覆盖。 我想我在语法上遗漏了一些东西——但找不到足够相关的例子来让它工作。

我希望得到:

male_40_50

a_male_40_50_12

相反,我得到:

[1] "male_40_50"

[1] "a_< S4 object of class \"Config\">_12"

您使用 setMethod 的示例不适用于 R 4.1 中的参考类。 但是您可以使用 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)

不幸的是,这在您的 list() 案例中也不起作用。

暂无
暂无

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

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