Writing an S4 generic method with two arguments

好久不见. 提交于 2019-12-13 04:26:16

问题


I am trying to define my own S4 class with a generic method.

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) {
    object@the.factor * n
})
cat(sprintf('ActOnNumber(multobj, 4) = %.2f\n', ActOnNumber(multobj, 4)))

However, when I source the file containing the above code, I get an error.

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

What is the correct way to define the ActOnNumber function?


回答1:


The standardGeneric() function is expecting the name of the function being made a generic, nothing more. So

setGeneric("ActOnNumber", function(object, n) {
    standardGeneric("ActOnNumber")
})


来源:https://stackoverflow.com/questions/21963291/writing-an-s4-generic-method-with-two-arguments

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!