简体   繁体   中英

Create new S3 class methods in R

I'm writing a package in which I would like to create a new generic method, called "analyze", wich do different things according to the argument class. Similar to print that has print.lm , print.aov etc.

In the R folder of my package, I created two files, "analyze.lm" and "analyze.aov" that contain eponym functions. However, if I run analyze(fit) on an lm object, it does nothing because R only recognizes analyze.lm and not the root function ("analyze" only).

I've tried adding an "analyze.R" file, which either contained setMethod() (but that errored), setGeneric("analyze", function(x) attributes(x)) (but that did not solve the issue) or an analyze() function that prints "NULL". However, if I then run analyze(fit) on an lm object, in prints NULL instead of running the analyze.lm class method.

How could I create a generic method, similar to base print , that behaves differently according to argument class, and than I maintained splitted in different files (analyze.lm.R, analyze.aov.R etc.). Thanks!

Add a generic function like this:

analyze <- function(object, ...){
    UseMethod("analyze")
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM