Search code examples
rt-test

Is there any way to control the output decimal places of the t-test function?


I'm using the built-in t-test function.

Code below:

t.test(
  mpg$cyl[mpg$model == "a4"],
  drill_df$Time_hr[mpg$model == "malibu"],
  alternative = "l",
  mu = 0,
  conf.level = 0.95,
)

Solution

  • Here is a solution. Write a function t_test calling t.test and then round the numbers in a lapply loop. The return value of lapply is a list, so class "htest" must be assigned manually before returning to caller.

    t_test <- function(..., d = 2){
      tt <- t.test(...)
      tt <- lapply(tt, function(x){
        if(is.numeric(x)) round(x, d) else x
      })
      class(tt) <- "htest"
      tt
    }
    
    t_test(
      mpg$cyl[mpg$model == "a4"],
      mpg$cyl[mpg$model == "malibu"],
      alternative = "l",
      mu = 0,
      conf.level = 0.95,
    )
    #   Welch Two Sample t-test
    #
    #data:  mpg$cyl[mpg$model == "a4"] and mpg$cyl[mpg$model == "malibu"]
    #t = -0.54, df = 8.63, p-value = 0.3
    #alternative hypothesis: true difference in means is less than 0
    #95 percent confidence interval:
    # -Inf 0.83
    #sample estimates:
    #mean of x mean of y 
    #     4.86      5.20