Вопрос

I'm not an expert on S4 but started after getting some help online. The following code works fine and now I want to set default value of alpha=0.05 if alpha is missing in call.

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)
Это было полезно?

Решение

You need to use the prototype argument.

From the help page of ?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.

So we can do something this

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
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top