函數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
希望它有幫助!
太好了!謝謝,這正是我正在尋找的。 – user2617763 2014-12-10 14:57:47
高興地幫助:) – LyzandeR 2014-12-10 15:00:20