May you correct my loop function. I want to calculate correlation of colomns of my matrices a and b. The output should be a loop of correlation of the first 3 rows of a and b and then the remaining 3(not a correlation matrix). My code is below.
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
the correct answer should be a matrix with the two rows below, respectively
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
on corrs[i] , change it to corrs[i,]