rexportxtablesignificant-digitsreporters

R : round p values to two significant digits in xtable and ReporteRs export to Latex/Office/LibreOffice


I am using a combination of xtable, rtable and ReporteRs to export summary tables of various objects (aov, glm's, lm's etc) to Latex/Word/Powerpoint. I'm not so fond of the default way, however, in which p values are given with a fixed number of digits after the comma. Instead I would prefer that it would give me p values in a similar format as one would get with base R function format.pval() with digits=2, i.e. give p values rounded to two significant digits - in this case 4.2e-17 and 0.25).

E.g.

ctl = c(4.17,5.58,5.18,6.11,4.50,4.61,5.17,4.53,5.33,5.14)
trt = c(4.81,4.17,4.41,3.59,5.87,3.83,6.03,4.89,4.32,4.69)
group = gl(2, 10, 20, labels = c("Ctl","Trt"))
weight = c(ctl, trt)
fit = lm(weight ~ group)
s=summary(fit)
s

Coefficients:
            Estimate Std. Error t value Pr(>|t|)    
(Intercept)   4.8465     0.1557  31.124   <2e-16 ***
group1        0.1855     0.1557   1.191    0.249    

library(xtable)
library(rtable)
library(ReporteRs)
tab=as.FlexTable(xtable(s))
tab

enter image description here

I would like to have the p-values formatted in a similar way as in summary(fit), however (right aligned, rounded to two significant digits, in this case 4.2e-17 and 0.25). Anybody any idea how this could be achieved in a generic way, ideally for the p values given by all the objects supported by xtable?

EDIT: with the help below I now made a [small package export] with helper functions table2doc, table2ppt and table2html to export the previously shown R stats object to Word, Powerpoint or HTML (and with function graph2ppt and graph2doc to export the currently active graph to Powerpoint or Word), see https://cran.r-project.org/web/packages/export/index.html and https://github.com/tomwenseleers/export


Solution

  • Define a helper function that will look for a signature of a p-value, which I am taking to be those colnames that have "Pr" in them:

    xtable2 <- function(x, ...) {  sm <- x[['coefficients']]; ncol <- ncol(sm)
                                 whch<- grep("Pr", colnames(sm))
                                 digs <- rep(4, ncol+1); digs[whch+1] <- 2
                                 disp <-rep("f", ncol+1); disp[whch+1] <- "g"
                      xtable(x, digits= digs, display=disp, ...) }
    
    > tab <- as.FlexTable(xtable2(s)); tab
    

    enter image description here