将插槽的缺失值设置为默认值

时间:2014-01-14 15:00:21

标签: r s4

我不是S4的专家,而是在网上获得一些帮助后开始的。以下代码工作正常,现在我想设置默认值alpha = 0.05如果调用中缺少alpha。任何帮助将受到高度赞赏。感谢

setClass(Class = "Test",
         representation = representation(
                                          data    = "data.frame",
                                          rep     = "numeric",
                                          MSE     = "numeric",
                                          alpha   = "numeric"
                                       )
         )


setMethod(
            f = "initialize",
            signature = "Test",
            definition = function(.Object, data, rep, MSE, alpha)
            {
                .Object@data  <- data
                .Object@rep   <- rep
                .Object@MSE   <- MSE
                .Object@alpha <- alpha
                return(.Object)
            }
          )


new(Class= "Test", data = Data, rep = 4, MSE = 1.8, alpha = 0.1)

1 个答案:

答案 0 :(得分:3)

您需要使用prototype参数。

?setClass

的帮助页面
  

prototype:一个对象,为此提供插槽的默认数据             类。默认情况下,每个都将是原型对象             超类。如果提供,使用“原型”调用将             进行一些检查。

所以我们可以做点什么

if(isClass("Test")) removeClass("Test")

setClass(Class = "Test",
         representation = representation(
         data    = "data.frame",
         rep     = "numeric",
         MSE     = "numeric",
         alpha   = "numeric"
         ),
         prototype = list(
         alpha = 0.05
         )
         )

new("Test", data = data.frame(1), rep = 4, MSE = 2.2)
## An object of class "Test"
## Slot "data":
##   X1
## 1  1

## Slot "rep":
## [1] 4

## Slot "MSE":
## [1] 2.2

## Slot "alpha":
## [1] 0.05