R:多次弗里德曼测试

时间:2014-12-05 15:11:40

标签: r loops statistics

多次进行同一次测试时有点问题。

我使用friedman.test来测试配对样本的变化。函数本身没有问题,我使用脚本为每列提供了预期的结果:

friedman.test(Variable ~ Time | Patient, data=table1)

然而,我已经为每位患者测量了几个变量(在几个时间点)。我可以使用上面的脚本对每个变量进行测试,但我想在一组选定的变量上按顺序自动执行。我尝试在向量或列表中输入我想要测试的变量,并使用向量/列表作为“变量”参数,但它不起作用。

有人能指出我正确的方向来进行这种类型的循环吗?

谢谢! SEB

2 个答案:

答案 0 :(得分:0)

函数as.formula()是关键。我将用一个小例子来解释。

来自内置的warpbreaks数据集(请参阅?friedman.test):

wb <- aggregate(warpbreaks$breaks,
                by = list(w = warpbreaks$wool,
                          t = warpbreaks$tension),
                FUN = mean)

> friedman.test(x ~ w | t, data = wb)

    Friedman rank sum test

data:  x and w and t
Friedman chi-squared = 0.3333, df = 1, p-value = 0.5637

现在让我们假设为了简单起见,我们要在循环而不是x中测试3个变量:

(对于这个例子,我每次都会使用x变量,因为它是一个演示)

myvariables <- c('x','x','x')  #this is your vector with all of the variables you will use

for ( i in myvariables) {  #and this block is the loop
  formula_text <- sprintf('%s ~ w | t', i) #writes the formula as text
  a <- as.formula(formula_text) #converts text to formula
  print(friedman.test(a, data = wb)) #runs as wanted!
}

以上循环输出:

    Friedman rank sum test

data:  x and w and t
Friedman chi-squared = 0.3333, df = 1, p-value = 0.5637


    Friedman rank sum test

data:  x and w and t
Friedman chi-squared = 0.3333, df = 1, p-value = 0.5637


    Friedman rank sum test

data:  x and w and t
Friedman chi-squared = 0.3333, df = 1, p-value = 0.5637

希望它有所帮助!

答案 1 :(得分:0)

尝试以下方法:

varnames <- c("Variable1","Variable2")

for (curvar in varnames) {
print(curvar)
print(friedman.test(table1[,curvar] ~ Time | Patient, data=table1)
}