有什么方法可以控制t检验功能的输出小数位吗?

问题描述

我正在使用内置的t-test函数

以下代码

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的返回值是一个列表,因此在返回给调用者之前必须手动分配类"htest"

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