Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

override S3 methods in base R

Tags:

r

r-s3

I am attempting to over-ride the print.anova() function from the R stats package within a local package that I use when teaching. Basically, I want to remove the printing of the heading and add a "total" row without creating a new function (e.g., ANOVA()) with a new class.

The function looks like the following:

print.anova <- function(x,digits=max(getOption("digits")-2,3),
 signif.stars=getOption("show.signif.stars"),totalSS=TRUE,rm.heading=TRUE,...) {
  if (!any(grepl("Res.Df",colnames(x)))) {         # exclusion for multiple lm objects
    if (!any(grepl("Levene",attr(x,"heading")))) { # exclusion for levenes.test
      if (totalSS) {                               # add total SS row
        x <- rbind(x,c(sum(x$Df),sum(x[,"Sum Sq"]),NA,NA,NA))
        row.names(x)[dim(x)[1]] <- "Total"
      }
    }
  }
  if (rm.heading) attr(x,"heading") <- NULL        # remove heading
  stats::print.anova(x,digits=digits,signif.stars=signif.stars,...)
  invisible(x)
}

My problem is that I am not sure whether to export this as a function, a method, an S3method, some combination of those, or something else entirely. For example, when I try this (part of roxygenize code):

#'@export

I get the following warning when running Rcmd check:

S3 methods shown with full name in documentation object 'print.anova':
  'print.anova'

but the function works as expected when I load my package.

However, if I try this:

#'@method print anova
#'@S3method print anova

I dont' get any warnings or errors with Rcmd check but when I try to use the function in R it finds the original function in the stats package namespace. Furthermore, if I do this

getAnywhere(print.anova)

I get this

2 differing objects matching ‘print.anova’ were found in the following places
  package:stats
  registered S3 method for print from namespace stats
  namespace:NCStats
  namespace:stats

Finally, for this version (not using export, but using method and S3method), my roxygen-developed namespace has the following item in it

S3method(print,anova)

Leading to my confusion is that I seem to have had success doing something similar with other functions (e.g., using the method and S3method version with print.summary.lm).

I would appreciate any help in my understanding what I am doing wrong here (or how I can ultimately accomplish this goal). Thank you in advance for any help.

p.s., for what it is worth, I am on Windows 7 (32-bit), R 2.15.2, and using RStudio.

like image 442
D Ogle Avatar asked Dec 21 '12 21:12

D Ogle


1 Answers

Instead of trying to override the print.anova function you could create your own class which is essentially identical to the anova class. Create an as.myanova function which will turn an anova object into an object of mynanova then write your print.myanova function.

like image 90
Michael Avatar answered Oct 29 '22 09:10

Michael