首页 > 解决方案 > 如何使函数返回特定位数

问题描述

我一直在使用一个函数来计算 t 检验,使用每个条件下的均值、标准差和 n。

ttest <- function(m1,m2,s1,s2,n1,n2,m0=0,equal.variance=FALSE)
{
  if( equal.variance==FALSE ) 
  {
    se <- sqrt( (s1^2/n1) + (s2^2/n2) )
    df <- ( (s1^2/n1 + s2^2/n2)^2 )/( (s1^2/n1)^2/(n1-1) + (s2^2/n2)^2/(n2-1) )
  } else
  {
    se <- sqrt( (1/n1 + 1/n2) * ((n1-1)*s1^2 + (n2-1)*s2^2)/(n1+n2-2) ) 
    df <- n1+n2-2
  }      
  t <- (m1-m2-m0)/se 
  sdpooled_n <- ((n1-1)*(s1^2)) + ((n2-1)*(s2^2)) 
  sdpooled_df <- ((n1 + n2) - 2) # 115
  sdpooled <- sqrt(sdpooled_n/sdpooled_df) 
  cohend <- (m1-m2)/sdpooled
  dat <- c(m1-m2, se, t, df,2*pt(-abs(t),df),cohend)    
  names(dat) <- c("Mean difference", "Std Error", "t","df", "p-value","Cohen's d")
  return(dat) 
}

它工作得很好,但是 R 使用科学记数法返回结果很烦人。例如,这段代码:

ttest(1.44,1.02,0.80,0.75,133,123,m0=0,equal.variance=FALSE)

回报:

Mean difference  Std Error     t             df             p-value         Cohen's d 
4.200000e-01     9.687725e-02  4.335383e+00  2.539507e+02   2.099250e-05    5.409679e-01 

相反,如果它会返回以下内容,那就太好了:

  Mean difference  Std Error     t             df             p-value         Cohen's d 
  0.42             0.10          4.34          253.95         0.000           0.54 

我试过使用 round() 函数(见下文),它工作得很好,除了它只显示 p 值的两位小数。除非 p<.001,否则我报告准确的 p 值很重要。

这是我更好的修改后的代码版本:

ttest <- function(m1,m2,s1,s2,n1,n2,m0=0,equal.variance=FALSE)
{
  if( equal.variance==FALSE ) 
  {
    se <- sqrt( (s1^2/n1) + (s2^2/n2) )
    df <- ( (s1^2/n1 + s2^2/n2)^2 )/( (s1^2/n1)^2/(n1-1) + (s2^2/n2)^2/(n2-1) )
  } else
  {
    se <- sqrt( (1/n1 + 1/n2) * ((n1-1)*s1^2 + (n2-1)*s2^2)/(n1+n2-2) ) 
    df <- n1+n2-2
  }      
  mdif <- m1-m2
  t <- (mdif-m0)/se 
  sdpooled_n <- ((n1-1)*(s1^2)) + ((n2-1)*(s2^2)) 
  sdpooled_df <- ((n1 + n2) - 2) # 115
  sdpooled <- sqrt(sdpooled_n/sdpooled_df) 
  cohend <- (m1-m2)/sdpooled
  p <- 2*pt(-abs(t),df)
  mdif <- round(mdif,2)
  se <- round(se,2)
  t <- round(t,2)
  df <- round(df,2)
  p <- round(p,3)
  cohend <- round(cohend,2)
  dat <- c(mdif, se, t, df,p,cohend)
  names(dat) <- c("Mean difference", "Std Error", "t","df", "p-value","Cohen's d")
  return(dat) 
}

但如您所见,它不会将 p 值返回到小数点后 3 位:

Mean difference  Std Error  t      df       p-value   Cohen's d 
0.42             0.10       4.34   253.95   0.00      0.54

标签: rfunctionoutputrounding

解决方案


您可以dat在第一个 ttest 函数中添加如下:

dat <-round(c(m1-m2, se, t, df,2*pt(-abs(t),df),cohend) , digits =2 )

最良好的祝愿!


推荐阅读