문제

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