I'm working on a collection of scripts and using s3 classes and methods to keep things a little cleaner.
The class structure has three levels.
- Level 1: data.frame
- Level 2: sample_report OR fix_report
- Level 3: stim_report
I want to write a function that ONLY takes data frames of class stim_report, then dispatches a different method depending on whether the stim_report inherits from sample_report or inherits from fix_report.
Obviously, I could do something like
myfunction.stim_report(df)
if ("sample_report" %in% class(df)) {
% do something
} else if ("fix_report" %in% class(df)) {
% do something
}
But that kind of defeats the purpose of methods dispatching.
Note that I need things to work so that the function will return an error if the class of the data frame isn't stim_report. So I suppose I could also do:
myfunction.fix_report(df)
if ("stim_report" %in% class(df)) {
% do something
} else {
stop("No method found")
}
myfunction.sample_report(df)
if ("stim_report" %in% class(df)) {
% do something
} else {
stop("No method found")
}
But again, this feels like it goes against the whole point of the S3 methods.
Is there a right way to do this?