R:我的循环有一个小错误,循环的各个部分都是正确的,除了完整的功能

R:我的循环有一个小错误,循环的各个部分都是正确的,除了完整的功能,r,loops,for-loop,R,Loops,For Loop,请你纠正我的循环函数。我想计算矩阵a和b的列的相关性。输出应该是a和b的前3行的相关循环,然后是其余3行(不是相关矩阵)。我的代码如下 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

请你纠正我的循环函数。我想计算矩阵a和b的列的相关性。输出应该是a和b的前3行的相关循环,然后是其余3行(不是相关矩阵)。我的代码如下

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

我不清楚您试图对代码做什么(请参阅有关代码格式的帮助),但如果我正确理解您问题的结尾,这不是您想要的吗:

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

OP似乎希望在循环中计算相关性,并在生成的矩阵中一次放置一个相关性。对于这个问题的未来读者,请注意这种风格的代码非常不类似R,通常速度慢且效率低,很少建议使用

定义矩阵:

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))

在corrs[i]上,将其更改为corrs[i,]

这是我想要的答案,但我希望它在循环中计算,而不是手动组合结果。我想要两个矩阵对应列的相关性,即列(a,d);(b,e)及(c,f)。结果应该是行的相关性1:3,然后是4:6,即每对列有两个相关性答案。我得到了错误。在我的原始代码中,只需将corrs[i]更改为corrs[i,]
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])
    }
}