R版本:
R version 2.15.2 (2012-10-26)
Platform: x86_64-apple-darwin9.8.0/x86_64 (64-bit)
我想制作一个S4类,该类使用nls.lm函数的输出对象(程序包:minpack.lm)作为插槽:
setOldClass("nls.lm")
setClass (
Class="TestClass",
representation=representation(
lmOutput = "nls.lm",
anumeric = "numeric"
)
)
现在,如果要在“构造函数”中调用此类,则可以执行以下操作(正确吗?):
myConstructor <- function()
{
return(new("TestClass"))
}
pippo <- myConstructor()
pippo
An object of class "TestClass"
Slot "lmOutput":
<S4 Type Object>
attr(,".S3Class")
[1] "nls.lm"
Slot "anumeric":
numeric(0)
并且对象“pippo”似乎已正确初始化。
如果我改用这段代码,则会报错:
myConstructor2 <- function()
{
pippo <- new("TestClass", anumeric=1000)
return(pippo)
}
pippo <- myConstructor2()
Error in validObject(.Object) :
invalid class “TestClass” object: invalid object for slot "lmOutput" in class "TestClass": got class "S4", should be or extend class "nls.lm"
似乎如果我要在一些新插槽中初始化,是否会导致S3类插槽出现问题?
关于如何避免此问题的任何线索?
谢谢
最佳答案
实际上,无参数构造函数也会返回一个无效的对象,只是未经测试
> validObject(new("TestClass"))
Error in validObject(new("TestClass")) :
invalid class "TestClass" object: invalid object for slot "lmOutput"
in class "TestClass": got class "S4", should be or extend class "nls.lm"
解决方案是提供适当的原型(prototype),也许
setClass (
Class="TestClass",
representation=representation(
lmOutput = "nls.lm",
anumeric = "numeric"
),
prototype=prototype(
lmOutput=structure(list(), class="nls.lm")
)
)
关于r - 使用S3虚拟类作为S4类的插槽,出现错误: got class "S4",应该是或扩展类 "nls.lm",我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/13841400/