Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In R, how can I set a generic method on a class from another package?

I am using the zoo class in my own packages. I would like to set a generic method with type zoo:

setMethod(
    "doWork", 
    signature = c("zoo"), 
    definition = function(x) {

        # Do work... 
    })

However, this gives me the error:

in method for ‘dowork’ with signature ‘"zoo"’: no definition for class “zoo”

How should I set the signature so that it refers to zoo::zoo?

like image 891
sdgfsdh Avatar asked May 14 '15 15:05

sdgfsdh


Video Answer


1 Answers

This is because the zoo class from the zoo package is not a formal S4 class. In order to use it with S4 methods you can use the setOldClass function which will set a S3 class as a formally defined class. Once you do this you should be able to use the class however you wish with the methods. Starting a new package (which I just call 'test') with the following file (please note the use of roxygen2).

methods.R

#' @import zoo
setOldClass("zoo")

setGeneric("doWork", function(x){
    standardGeneric("doWork")
})

#' @export
setMethod(
    "doWork", 
    signature = c("zoo"), 
    definition = function(x) {

        print("IT WORKS!!!")
    }
)

test the function

library(test) # if not already loaded
library(zoo)
x.Date <- as.Date("2003-02-01") + c(1, 3, 7, 9, 14) - 1
x <- zoo(rnorm(5), x.Date)
doWork(x)
[1] "IT WORKS!!!"
like image 188
cdeterman Avatar answered Oct 19 '22 04:10

cdeterman