带有两个分组变量的T检验

时间:2015-07-12 10:52:58

标签: r

我想对性别(男性,女性)之间的年龄差异进行t检验,但需要额外的分组变量grp(a,b)。数据在数据帧(df)中。

这让整个样本按性别划分:

with(df, t.test(age~sex))

这让我按照整个样本分组:

with(df, t.test(age~grp))

我希望按性别和群体年龄划分,即b中女性与女性比较,b中男性与男性比较。

2 个答案:

答案 0 :(得分:2)

使用原生R:

lapply(split(df,df$sex),function(x)with(x, t.test(age~grp)))

$f

    Welch Two Sample t-test

data:  age by grp
t = 1.3978, df = 42.029, p-value = 0.1695
alternative hypothesis: true difference in means is not equal to 0
95 percent confidence interval:
 -3.241762 17.854665
sample estimates:
mean in group 1 mean in group 2 
       56.50000        49.19355 


$m

    Welch Two Sample t-test

data:  age by grp
t = 0.33265, df = 36.741, p-value = 0.7413
alternative hypothesis: true difference in means is not equal to 0
95 percent confidence interval:
 -7.457013 10.385584
sample estimates:
mean in group 1 mean in group 2 
       54.00000        52.53571 

答案 1 :(得分:1)

df <- data.frame(
  age = sample(x = 20:80, 100, TRUE),
  sex = sample(c("m", "f"), 100, TRUE),
  grp = sample(1:2, 100, TRUE)
)

library(plyr)

# Split df by "sex" and apply function to each subset of df. Returns a list of the return values.
dlply(.data = df, .variables = "sex", .fun = function(x) {
  with(x, t.test(age~grp))
})