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

标签 r s4

我不是 S4 方面的专家,但在网上获得一些帮助后开始了。下面的代码工作正常,现在如果调用中缺少 alpha,我想设置默认值 alpha=0.05。

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)

最佳答案

您需要使用prototype 参数。

来自?setClass的帮助页面

prototype: an object providing the default data for the slots in this class. By default, each will be the prototype object for the superclass. If provided, using a call to ‘prototype’ will carry out some checks.

所以我们可以做一些事情

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

关于r - 将插槽的缺失值设置为默认值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21116693/

相关文章:

r - 如何为继承的插槽定义 S4 原型(prototype)

r - 如何将 S4 插槽选择器 `@` 重载为通用函数

r - 如何计算与 S4 类关联的对象数量

r - 生成步骤链或步骤序列而不命名它们

r - 使用所选列中所有值的最大值有条件地更新某些列(data.table,r)

r - 通过 R 中的组查找 boolean 值是否为真

r - 带有 "["参数的 'missing' 的 S4 文档

R传单情节船方向

r - 量化灰度图像

r - S4 泛型中的可选参数