[R] Use generic functions, e.g. print, without UseMethod?

Rui Barradas ru|pb@rr@d@@ @end|ng |rom @@po@pt
Fri Aug 11 09:56:50 CEST 2023

Às 08:20 de 11/08/2023, Sigbert Klinke escreveu:
> Hello,
> I have defined a function 'equations(...)' which returns an object with 
> class 'equations'. I also defined a function 'print.equations' which 
> prints the object. But I did not use 'equations <- function(x, ...) 
> UseMethod("equations"). Two questions:
> 1.) Is this a sensible approach?
> 2.) If yes, are there any pitfalls I could run in later?
> Thanks
> Sigbert

You have to ask yourself what kind of objects are you passing to 
Do you need to have


specifically written for objects of class


These methods would act on the respective class, process those objects 
somewhat differently because they are of different classes and output an 
object of class "equation".
(If so, it is recommended to write a 'equations.default(...)' too.)

Methods such as print.equation or summary.equation are written when you 
want your new class to have functionality your new class' users are 
familiar with.

If, for instance, autoprint is on as it frequently is, users can see 
their "equation" by typing its name at a prompt. print.equation would 
display the "equation" in a way relevant to that new class.

But this does not mean that the function that *creates* the object needs 
to be generic, you only need a new generic to have methods processing 
inputs of different classes in ways specific to those classes.

Hope this helps,

Rui Barradas

More information about the R-help mailing list