6

版本:

    R version 2.15.2 (2012-10-26)
    Platform: x86_64-apple-darwin9.8.0/x86_64 (64-bit)

我想制作一个使用 nls.lm (包: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"

似乎如果我想在新的一些插槽中进行初始化,这会导致 S3 类插槽出现问题?

关于如何避免这个问题的任何线索?

谢谢

4

1 回答 1

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")
    )
  )
于 2012-12-12T14:40:32.573 回答