R:多次弗里德曼测试



多次进行相同的测试时会出现一个小问题。

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

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

但是,我已经为每个患者测量了几个变量(在几个时间点上)。我可以使用上面的脚本对每个变量进行测试,但我想在一组选定的变量上按顺序自动进行测试。我尝试在向量或列表中输入我要测试的变量,并使用向量/列表作为"变量"参数,但没有奏效。

有人可以为这种类型的循环指出正确的方向吗?

谢谢!塞布

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

从内置的 warpbreak 数据集(见?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

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

(对于此示例,我每次都会使用 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

希望对您有所帮助!

尝试以下操作:

varnames <- c("Variable1","Variable2")
for (curvar in varnames) {
print(curvar)
print(friedman.test(table1[,curvar] ~ Time | Patient, data=table1)
}

最新更新