2014-12-05 34 views
1

多次執行相同測試時出現小問題。R:多次弗裏德曼測試

我正在使用friedman.test來測試配對樣本的變化。該函數本身不會產生問題,我對使用腳本每一列的預期結果:

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

但是我已經爲每個患者測量(在幾個時間點)的幾個變量。我可以使用上面的腳本對每個變量進行一次測試,但是我想按順序並自動地對所選的一組變量進行測試。我嘗試在矢量或列表中輸入想要測試的變量,並使用vector/list作爲「變量」參數,但它沒有奏效。

有人可以指出我正確的方向爲這種類型的循環?

謝謝! Seb

回答

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 

希望它有幫助!

+0

太好了!謝謝,這正是我正在尋找的。 – user2617763 2014-12-10 14:57:47

+0

高興地幫助:) – LyzandeR 2014-12-10 15:00:20

0

嘗試以下操作:

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

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