[英]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.