有没有办法控制t检验函数的输出小数位?

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

我正在使用内置的 t 检验函数。

代码如下:

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

这是一个解决方案。编写一个函数 t_test 调用 t.test,然后在 lapply 循环中舍入数字。 lapply 的 return 值是一个列表,因此 class "htest" 必须在 return 调用方之前手动分配。

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