Rでwelchのt検定(t-test)と効果量をさっくり出す

タイトルの通りです。t検定と効果量を同時に出してくれるパッケージを探したんですが,見つけられなかったので作ってみました。t検定を出して,効果量を出して,というのも繰り返すとけっこう手間なので多少は楽できるかなと。 自分用なので細かい設定を省いています。もちろん,カスタマイズはご自由にどうぞ。また,Rで自作関数を作るのははじめてなので,間違いがあったら教えて下さい。

なお,cohen's dに関しては種類(計算式)があるので気をつける必要があります。例えば,within(対応のあるデータ)ではデータ間に相関があるので,それを考慮したcohen's dがあります。個人的には,within/betweenというデザインを越えて,効果量で比較したいことが多いのであまり計算しません。

実施には以下のパッケージが必要です。

effsize

#welch検定と効果量を1回で出す関数 t.test.es を定義
t.test.es <- function(x, y, t.paired = FALSE, es.ci = 0.95, es.paired = FALSE, rm = FALSE)
{
  t <- t.test(x, y, paired = t.paired)
  es <- effsize::cohen.d(x, y, conf.level = es.ci, na.rm = rm, paired = es.paired)
  return(list(t,es))
}

t.test.es(x, y, t.paired, es.ci, es.paired, rm)

  • x = データ1
  • y = データ2
  • t.paired = t検定に対応があるか(TRUE or FALSE; デフォルトはFALSE)
  • es.ci = 効果量の信頼区間(デフォルトは0.95 = 95%)
  • es.paired = 対応があるcohen's dにするか(TRUE or FALSE; デフォルトはFALSE)
  • rm = 効果量算出時に欠損値を除外するか(TRUE or FALSE; デフォルトはFALSE)

例1(対応のないt検定)

library(effsize)

#welch検定と効果量を1回で出す関数 t.test.es を定義
t.test.es <- function(x, y, t.paired = FALSE, es.ci = 0.95, es.paired = FALSE, rm = FALSE)
{
  t <- t.test(x, y, paired = t.paired)
  es <- effsize::cohen.d(x, y, conf.level = es.ci, na.rm = rm, paired = es.paired)
  return(list(t,es))
}

#t検定と効果量算出
t.test.es(x = iris$Sepal.Length, y = iris$Sepal.Width)

出力

[[1]]

    Welch Two Sample t-test

data:  x and y
t = 36.463, df = 225.68, p-value < 2.2e-16
alternative hypothesis: true difference in means is not equal to 0
95 percent confidence interval:
 2.63544 2.93656
sample estimates:
mean of x mean of y 
 5.843333  3.057333 


[[2]]

Cohen's d

d estimate: 4.210417 (large)
95 percent confidence interval:
   lower    upper 
3.802906 4.617929 

例2(同じデータで対応のあるt検定)

library(effsize)

#welch検定と効果量を1回で出す関数 t.test.es を定義
t.test.es <- function(x, y, t.paired = FALSE, es.ci = 0.95, es.paired = FALSE, rm = FALSE)
{
  t <- t.test(x, y, paired = t.paired)
  es <- effsize::cohen.d(x, y, conf.level = es.ci, na.rm = rm, paired = es.paired)
  return(list(t,es))
}

#t検定と効果量算出
t.test.es(x = iris$Sepal.Length, y = iris$Sepal.Width, t.paired = TRUE,  es.ci = 0.95, es.paired = FALSE, rm = FALSE)

出力

[[1]]

    Paired t-test

data:  x and y
t = 34.815, df = 149, p-value < 2.2e-16
alternative hypothesis: true difference in means is not equal to 0
95 percent confidence interval:
 2.627874 2.944126
sample estimates:
mean of the differences 
                  2.786 


[[2]]

Cohen's d

d estimate: 4.210417 (large)
95 percent confidence interval:
   lower    upper 
3.802906 4.617929