【问题标题】:Setting missing value of slot to default value将槽的缺失值设置为默认值
【发布时间】:2020-09-09 06:04:58
【问题描述】:

我不是 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)

【问题讨论】:

    标签: r s4


    【解决方案1】:

    您需要使用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
    

    【讨论】:

    • 感谢@dickoa 的回答。我尝试了您给定的代码,但它引发了错误:Error in .local(.Object, ...) : argument "alpha" is missing, with no default。任何建议。我需要对 setMethod 进行任何更改吗?
    • @MYaseen208 删除您所做的setMethod 调用并在运行此示例之前删除该类。我更新了我的答案,向您展示如何删除课程
    猜你喜欢
    • 1970-01-01
    • 2019-07-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多