井出草平の研究ノート

まとめてT検定を行う その1[R]

こちらの方の解決法。

www.rpubs.com

おそらくこのブログを書いておられる方。 https://blog.goo.ne.jp/r-de-r

同じグループ間(治療群対プラセボ群)で異なる変数(年齢、身長、体重、罹病期間、疾患など)について複数のt検定(またはウィルコクソン検定)を行う必要があることがよくある。しかし、私の知る限り、これを補助する機能はない。

なぜかRは基礎分析に弱いのである。

サンプルデータ

library(survival)
data(kidney)

データ。

   id time status age sex disease frail
1   1    8      1  28   1   Other   2.3
2   1   16      1  28   1   Other   2.3
3   2   23      1  48   2      GN   1.9
4   2   13      0  48   2      GN   1.9
5   3   22      1  32   1   Other   1.2

lapplyを使った方法

lapply(kidney[,c("time", "age", "frail")], 
                       function(x) t.test(x ~ kidney$sex, var.equal = TRUE))

結果。

$time

    Two Sample t-test

data:  x by kidney$sex
t = -1.706, df = 74, p-value = 0.09221
alternative hypothesis: true difference in means is not equal to 0
95 percent confidence interval:
 -124.551228    9.651228
sample estimates:
mean in group 1 mean in group 2 
          59.30          116.75 


$age

    Two Sample t-test

data:  x by kidney$sex
t = -0.069294, df = 74, p-value = 0.9449
alternative hypothesis: true difference in means is not equal to 0
95 percent confidence interval:
 -7.970091  7.434376
sample estimates:
mean in group 1 mean in group 2 
       43.50000        43.76786 


$frail

    Two Sample t-test

data:  x by kidney$sex
t = 0.95032, df = 74, p-value = 0.345
alternative hypothesis: true difference in means is not equal to 0
95 percent confidence interval:
 -0.1872248  0.5286533
sample estimates:
mean in group 1 mean in group 2 
       1.310000        1.139286 
       

ややややこしいな、という印象がある。

自作関数を作っての方法

下記が作成された自作の関数。

multi.tests <- function(fun = t.test, df, vars, group.var, ...) {
    sapply(simplify = FALSE,                                    # sapply(simplify=T) better, elements named
           vars,                                                # loop on vector of outcome variable names
           function(var) {
               formula <- as.formula(paste(var, "~", group.var))# create a formula with outcome and grouping var.
               fun(data = df, formula, ...)                     # perform test with a given fun, default t.test
           }
           )
}

まとめてT検定を行う

res.multi.t.tests <-
    multi.tests(fun = t.test,
                df = kidney,
                vars = c("time","age","frail"),
                group.var = "sex",
                var.equal = TRUE)
res.multi.t.tests

P値だけ取り出す

data.frame(p.value = sapply(res.multi.t.tests, getElement, name = "p.value"))
         p.value
time  0.09221072
age   0.94494267
frail 0.34504459