rxtabler-carmanova

xtable for MANOVA object obtained with car package


I wonder how to get xtable of MANOVA object obtained with car package. Here is MWE:

library(xtable)
library(car)
MANOVA <- Anova(lm(cbind(Al, Fe, Mg, Ca, Na) ~ Site, data=Pottery))
xtable(MANOVA)

Error in UseMethod("xtable") : no applicable method for 'xtable' applied to an object of class "Anova.mlm"


Solution

  • The problem is that xtable has a method for objects of class anova, but the car package's Anova function returns an object of class anova.mlm. I found a fix at https://stat.ethz.ch/pipermail/r-help/2009-June/201478.html:

    library(xtable)
    library(car)
    
    # Create some example data
    Pottery <- data.frame(
      "Al" = rnorm(10),
      "Fe" = rnorm(10),
      "Mg" = rnorm(10),
      "Ca" = rnorm(10),
      "Na" = rnorm(10),
      "Site" = sample(LETTERS[1:2], 10, replace = TRUE))
    
    # Create a custom function handling `anova.mlm` objects
    xtable.Anova.mlm <- function (x, ...) {
      test <- x$test
      repeated <- x$repeated
      ntests <- length(x$terms)
      tests <- matrix(NA, ntests, 4)
      if (!repeated)
        SSPE.qr <- qr(x$SSPE)
      for (term in 1:ntests) {
        eigs <- Re(eigen(qr.coef(if (repeated) qr(x$SSPE[[term]]) else
          SSPE.qr,
          x$SSP[[term]]), symmetric = FALSE)$values)
        tests[term, 1:4] <- switch(test, Pillai = stats:::Pillai(eigs,
          x$df[term], x$error.df), Wilks = stats:::Wilks(eigs,
            x$df[term], x$error.df), `Hotelling-Lawley` = stats:::HL(eigs,
              x$df[term], x$error.df), Roy = stats:::Roy(eigs,
                x$df[term], x$error.df))
      }
      ok <- tests[, 2] >= 0 & tests[, 3] > 0 & tests[, 4] > 0
      ok <- !is.na(ok) & ok
      tests <- cbind(x$df, tests, pf(tests[ok, 2], tests[ok, 3],
        tests[ok, 4], lower.tail = FALSE))
      rownames(tests) <- x$terms
      colnames(tests) <- c("Df", "test stat", "approx F", "num Df",
        "den Df", "Pr(>F)")
      tests <- structure(as.data.frame(tests), heading = paste("\nType ",
        x$type, if (repeated)
          " Repeated Measures", " MANOVA Tests: ", test, " test
    statistic",
        sep = ""), class = c("anova", "data.frame"))
      #    print(tests)
      #    invisible(x)
      xtable(tests)
    }
    
    
    MANOVA <- Anova(lm(cbind(Al, Fe, Mg, Ca, Na) ~ Site, data=Pottery))
    
    xtable(MANOVA)
    
    % latex table generated in R 2.15.2 by xtable 1.7-1 package
    % Tue Jun 11 20:49:51 2013
    \begin{table}[ht]
    \centering
    \begin{tabular}{lrrrrrr}
    \hline
    & Df & test stat & approx F & num Df & den Df & Pr($>$F) \\ 
    \hline
    Site & 1 & 0.61 & 1.24 & 5 & 4 & 0.4288 \\ 
    \hline
    \end{tabular}
    \end{table}