2011-07-16 25 views
-1

您可否糾正我的循環功能。我想計算我的矩陣a和b的colomns的相關性。輸出應該是a和b前3行相關的循環,然後是剩餘的3(不是相關矩陣)。我的代碼如下。R:我的循環中的小錯誤 - 循環的各個部分都是正確的,除了全功能

a=read.table("H:/cor1.txt",header=T) 
b=read.table("H:/cor2.txt",header=T) 
t=as.matrix(a) 
y 

      d  e f 
    [1,] 6 -5 7 
    [2,] 7 -4 4 
    [3,] 8 -3 3 
    [4,] 9 -2 3 
    [5,] 10 -1 9 
    [6,] 11  0 7 


t 
     a  b c 
    [1,] 1 -1 4 
    [2,] 2 -2 6 
    [3,] 3 -3 9 
    [4,] 4 -4 12 
    [5,] 5 -5 6 
    [6,] 6 -6 5 

y=as.matrix(b) 
n=3 #number to consider at a time 
runs=2 #runs multiplied by number of shares be looked at 
Corrs=matrix(0, nrow=2,3) #100 is number of shares being looked at 
for (i in 1:runs){ 
    index_start = n*(i-1)+1 #replace 100 with days in a quater 
    index_end = n*i #replace 100 with days in a quater 
    use_index = index_start:index_end 
    Corrs[i] = diag(cor(t[use_index,],y[use_index,])) 
} 

Warning messages: 

1: In Corrs[i] = diag(cor(t[use_index, ], y[use_index, ])) : 
    number of items to replace is not a multiple of replacement length 
2: In Corrs[i] = diag(cor(t[use_index, ], y[use_index, ])) : 
    number of items to replace is not a multiple of replacement length 

Corrs 

    [,1] [,2] [,3] 
[1,] 1 0 0 
[2,] 1 0 0 

正確的答案應與下面的兩行的矩陣,分別

diag(cor(t[1:3,],y[1:3,])) 

[1] 1.0000000 -1.0000000 -0.9226129 

diag(cor(t[4:6,],y[4:6,])) 

[1] 1.0000000 -1.0000000 -0.8934051 

回答

0

[I],將其更改爲可兒家族[我]

0

我爲你正在嘗試做你的代碼(請參閱有關幫助什麼很不清楚代碼格式化),但如果我正確地理解你的問題的結束,這不就是你想要的東西:

rbind(diag(cor(t[1:3,],y[1:3,])),diag(cor(t[4:6,],y[4:6,])) 

編輯

OP似乎想要在循環中計算出的相關性,並在結果矩陣中一次放置一個。對於這個問題的未來觀衆,請注意,這種代碼風格非常不類似,通常速度慢,效率低,而且很少可取。

定義矩陣:

y <- cbind(6:11,(-5):(0),c(7,4,3,3,9,7)) 
x <- cbind(1:6,(-1):(-6),c(4,6,9,12,6,5)) 

我用x代替t因爲t是非常常用的矩陣函數(轉置)的名稱,所以我更喜歡以避免使用,作爲一個矩陣的名稱。

初始化結果矩陣和循環:在Corrs的

result <- matrix(NA,2,3) 
for (i in 1:2){ 
    for (j in 1:3){ 
     result[i,j] <- cor(x[(3*(i-1) + 1):(3*(i-1) + 3),j],y[(3*(i-1) + 1):(3*(i-1) + 3),j]) 
    } 
} 
+0

這是我想要的答案,但我希望它在計算循環而不是手動組合結果。我需要2個矩陣的相應列的相關性,即列(a,d);(b,e)和(c,f)。結果應該是行1:3和4:6的相關性,即每對列的兩個相關答案。 – rder

+0

我得到了錯誤。在我原來的代碼中,只需將corrs [i]更改爲corrs [i,] – rder