函数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
现在,为了简单起见,假设我们有 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
希望对你有帮助!