2014-01-14 42 views
2

我不是S4的專家,但是在獲得一些在線幫助後開始工作。下面的代碼工作正常,現在我想設置α= 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) 
      { 
       [email protected] <- data 
       [email protected] <- rep 
       [email protected] <- MSE 
       [email protected] <- alpha 
       return(.Object) 
      } 
     ) 


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

回答

3

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

感謝@dickoa。我試着給你的代碼,但它會引發錯誤:'.local(.Object,...)錯誤: 參數「alpha」丟失,沒有默認值。任何建議。我需要setMethod中的任何更改嗎? – MYaseen208

+0

@ MYaseen208在運行此示例之前,除去您所做的setMethod調用並刪除該類。我更新了我的答案,向您展示如何刪除課程 – dickoa