Question

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?

Was it helpful?

Solution

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

setGeneric("ActOnNumber", function(object, n) {
    standardGeneric("ActOnNumber")
})
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top