我想对一堆变量应用 t 检验。下面是一些模拟数据
d <- data.frame(var1=rnorm(10),
var2=rnorm(10),
group=sample(c(0,1), 10, replace=TRUE))
# Is there a way to do this in some sort of loop?
with(d, t.test(var1~group))
with(d, t.test(var2~group))
# I tried this but the loop did not give a result!?
varnames <- c('var1', 'var2')
for (i in 1:2) {
eval(substitute(with(d, t.test(variable~group)),
list(variable=as.name(varnames[i]))))
}
此外,是否可以从 t 检验的结果中提取值(例如,两组均值,p 值),以便循环将在变量之间生成一个整洁的平衡表?换句话说,我想要的最终结果不是一堆相互叠加的 t 检验,而是这样的表格:
Varname mean1 mean2 p-value
Var1 1.1 1.2 0.989
Var2 1.2 1.3 0.912