您可否糾正我的循環功能。我想計算我的矩陣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
這是我想要的答案,但我希望它在計算循環而不是手動組合結果。我需要2個矩陣的相應列的相關性,即列(a,d);(b,e)和(c,f)。結果應該是行1:3和4:6的相關性,即每對列的兩個相關答案。 – rder
我得到了錯誤。在我原來的代碼中,只需將corrs [i]更改爲corrs [i,] – rder