rlatexknitrsweavernw

Printing p-values with <0.001


I wonder how to put <0.001 symbol if p-value is small than 0.001 to be used in Sweave.

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)
lm.D9 <- lm(weight ~ group)
summary(lm.D9)$coef

           Estimate Std. Error  t value     Pr(>|t|)
(Intercept)   4.8465  0.1557174 31.12368 4.185248e-17
group1       -0.1855  0.1557174 -1.19126 2.490232e-01

Desired Output

           Estimate Std. Error  t value     Pr(>|t|)
(Intercept)   4.8465  0.1557174 31.12368   <0.001
group1       -0.1855  0.1557174 -1.19126    0.249

Solution

  • There are two main functions that I use, format.pval and this one that I ripped from gforge and tweaked.

    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)
    lm.D9 <- lm(weight ~ group)
    tmp <- data.frame(summary(lm.D9)$coef)
    tmp <- setNames(tmp, colnames(summary(lm.D9)$coef))
    tmp[ , 4] <- format.pval(tmp[ , 4], eps = .001, digits = 2)
    
    tmp
    #             Estimate Std. Error  t value Pr(>|t|)
    # (Intercept)    5.032  0.2202177 22.85012   <0.001
    # groupTrt      -0.371  0.3114349 -1.19126     0.25
    

    I like this one because it removes precision from pvalues > .1 (or whatever threshold you like if you want something different; that is, regardless of digits, it only keeps two decimal places if the values is > .1), keeps trailing zeros (see example below), and adds in the < like you want for some level of precision (here 0.001).

    pvalr <- function(pvals, sig.limit = .001, digits = 3, html = FALSE) {
    
      roundr <- function(x, digits = 1) {
        res <- sprintf(paste0('%.', digits, 'f'), x)
        zzz <- paste0('0.', paste(rep('0', digits), collapse = ''))
        res[res == paste0('-', zzz)] <- zzz
        res
      }
    
      sapply(pvals, function(x, sig.limit) {
        if (x < sig.limit)
          if (html)
            return(sprintf('&lt; %s', format(sig.limit))) else
              return(sprintf('< %s', format(sig.limit)))
        if (x > .1)
          return(roundr(x, digits = 2)) else
            return(roundr(x, digits = digits))
      }, sig.limit = sig.limit)
    }
    

    And examples:

    pvals <- c(.133213, .06023, .004233, .000000134234)
    pvalr(pvals, digits = 3)
    # [1] "0.13"    "0.060"   "0.004"   "< 0.001"