2014-02-23 70 views
0

我想用一個通用的方法來定義我自己的S4類。用兩個參數編寫一個S4泛型方法

setClass("MultiplyObject", representation(the.factor = "numeric")) 
# Create a new instance of a class with the "new" method 
multobj <- new("MultiplyObject", the.factor = 3) 
# Create a new generic function definition 
setGeneric("ActOnNumber", function(object, n) { 
    standardGeneric("ActOnNumber", n) 
}) 
# Define the ActOnNumber method for the MultiplyObject class 
setMethod("ActOnNumber", signature(object = "MultiplyObject", n = "numeric"), 
     function(object, n) { 
    [email protected] * n 
}) 
cat(sprintf('ActOnNumber(multobj, 4) = %.2f\n', ActOnNumber(multobj, 4))) 

但是,當我輸入包含上述代碼的文件時,出現錯誤。

> source('tests4.R') 
Error in ActOnNumber(multobj, 4) : 
    expected a generic function or a primitive for dispatch, got an object of class "numeric" 

什麼是定義ActOnNumber函數的正確方法?

回答

4

standardGeneric()函數期望函數的名稱被作爲泛型,僅此而已。所以

setGeneric("ActOnNumber", function(object, n) { 
    standardGeneric("ActOnNumber") 
}) 
相關問題