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?

有帮助吗?

解决方案

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

setGeneric("ActOnNumber", function(object, n) {
    standardGeneric("ActOnNumber")
})
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top