R版本:
R version 2.15.2 (2012-10-26)
Platform: x86_64-apple-darwin9.8.0/x86_64 (64-bit)
我想创建一个使用nls.lm函数的输出对象(package:minpack.lm)作为插槽的S4类:
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"
似乎如果我想在新的一些插槽中进行INIT,这会产生S3类插槽的问题?
有关如何避免此问题的任何线索?
由于
答案 0 :(得分:3)
实际上,无参数构造函数也会返回一个无效对象,它只是没有经过测试
> 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"
解决方案是提供适当的原型,也许
setClass (
Class="TestClass",
representation=representation(
lmOutput = "nls.lm",
anumeric = "numeric"
),
prototype=prototype(
lmOutput=structure(list(), class="nls.lm")
)
)