晚上好,
我有以下数据框:
Sex A B C D E
M 1 20 45 42 12
F 2 10 32 23 43
M 39 32 2 23 43
M 24 43 2 44 12
F 11 3 4 4 11
我将如何使用 apply 函数计算性别变量上面列出的数据框的每个数值变量的双样本 t 检验。结果应该是一个包含五个的矩阵
列:F.mean(女性数值变量的平均值),M.mean(数值变量的平均值
对于男性)、t(对于 t 统计量)、df(对于自由度)和 p(对于 p 值)。
谢谢!!
最佳答案
这是一个使用 apply
的选项有 margin 2
out = apply(data[,-1], 2, function(x){
unlist(t.test(x[data$Sex == 'M'], x[data$Sex == 'F'])[c(1:3,5)],
recursive=FALSE)
})
#> out
# A B C D E
#statistic.t 1.2432059 3.35224633 -0.08318328 1.9649783 -0.2450115
#parameter.df 2.5766151 2.82875770 2.70763487 1.9931486 1.8474695
#p.value 0.3149294 0.04797862 0.93946696 0.1887914 0.8309453
#estimate.mean of x 21.3333333 31.66666667 16.33333333 36.3333333 22.3333333
#estimate.mean of y 6.5000000 6.50000000 18.00000000 13.5000000 27.0000000
数据
data = structure(list(Sex = structure(c(2L, 1L, 2L, 2L, 1L), .Label = c("F",
"M"), class = "factor"), A = c(1L, 2L, 39L, 24L, 11L), B = c(20L,
10L, 32L, 43L, 3L), C = c(45L, 32L, 2L, 2L, 4L), D = c(42L, 23L,
23L, 44L, 4L), E = c(12L, 43L, 43L, 12L, 11L)), .Names = c("Sex",
"A", "B", "C", "D", "E"), class = "data.frame", row.names = c(NA,
-5L))
关于R 编程 : Calculate two-sample t-test for a data frame with formatting,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35956401/