2013-03-05 90 views
1

我想將兩個循環轉換爲一個應用函數,其中一個用於循環,希望這會加快我的計算速度。我知道使用apply並不能保證更快的計算,但我想試試看(也適合學習經驗來熟悉apply)R:嘗試使用apply來轉換for循環

我想要做的是;

計算兩個矩陣的每一行的皮爾森相關係數,也得到p值。

矩陣雙方都有約3000 X 100

現在我的代碼看起來是這樣的,它已經運行了天維...

cnt <- 1; 
res_row1 <- c(); 
res_row2 <- c(); 
res_corr <- c(); 
res_pval <- c(); 
for (i in (1:dim(m1)[1])) { 
    for (j in (1:dim(m2)[1])) { 
    c <- cor.test(as.matrix(m1[i,]), as.matrix(m2[j,])); 

    res_row1[cnt] <- rownames(m1)[i]; 
# need both row names in the output files 
    res_row2[cnt] <- rownames(m2)[j]; 

    res_corr[cnt] <- c$estimate; 
    res_pval[cnt] <- c$p.value; 
# Storing the results for output 

cnt<-cnt+1; 


    } 
    comp <- (i/dim(m1[1]) * 100; 
    cat(sprintf("Row number of file 1 = %f | %f percent complete \n", i, comp)) 

} 
results <- cbind(res_row1, res_row2, res_corr, res_pval) 

你們能幫助我嗎?

+1

你的問題是不是(真的)'for'環vs'apply',而是你在[hell]的第二個圈子裏(http://www.burns-stat.com/pages/Tutor/R_inferno.pdf)。 – joran 2013-03-05 15:52:13

+0

謝謝!剛剛在幾周前開始使用R。一個不錯的開眼界:) – 2013-03-05 18:51:09

回答

1

看一看的cor該手冊:

如果 「X」和「y」是矩陣,則協方差(或關聯)的「X」的列和列之間 ' y'被計算。

所以,我想嘗試:

cor(t(m1), t(m2)) 

對於p值,儘量使用雙apply功能:

R > x <- matrix(rnorm(12), 4, 3) 
R > y <- matrix(rnorm(12), 4, 3) 
R > cor(t(x), t(y)) 
     [,1] [,2] [,3]  [,4] 
[1,] 0.9364 0.8474 -0.7131 0.67342 
[2,] -0.9539 -0.9946 0.9936 -0.07541 
[3,] 0.8013 0.9046 -0.9752 -0.25822 
[4,] 0.3767 0.5541 -0.7205 -0.72040 
R > t(apply(x, 1, function(a) apply(y, 1, function(b) cor(b, a)))) 
     [,1] [,2] [,3]  [,4] 
[1,] 0.9364 0.8474 -0.7131 0.67342 
[2,] -0.9539 -0.9946 0.9936 -0.07541 
[3,] 0.8013 0.9046 -0.9752 -0.25822 
[4,] 0.3767 0.5541 -0.7205 -0.72040 
R > t(apply(x, 1, function(a) apply(y, 1, function(b) cor.test(b, a)$p.value))) 
     [,1] [,2] [,3] [,4] 
[1,] 0.2283 0.35628 0.49461 0.5297 
[2,] 0.1940 0.06602 0.07231 0.9519 
[3,] 0.4083 0.28034 0.14201 0.8337 
[4,] 0.7541 0.62615 0.48782 0.4879 
R > cor.test(x[1,], y[1,])$p.value 
[1] 0.2283 
R > cor.test(x[1,], y[2,])$p.value 
[1] 0.3563 
+0

非常感謝你!我的愚蠢的循環可以簡化成一條線,令我感到驚訝... – 2013-03-05 18:48:19

+0

哦,還有一件事。如果矩陣具有不同的維度(它們具有相同的列數但不同的行數),我可以做些什麼,我想這會導致雙重應用函數中的錯誤。 – 2013-03-05 18:58:42

+0

@JinhyunJu我剛試過。這裏似乎沒有問題。你能更新你在你的問題中嘗試過的嗎? – liuminzhao 2013-03-05 19:02:12