# [R] error on my loop function

Weidong Gu anopheles123 at gmail.com
Sat Jul 16 21:57:53 CEST 2011

```Hi,

In your loop, change Corrs[i] to Corrs[i,]

Weidong Gu

On Sat, Jul 16, 2011 at 12:02 PM, EdBo <n.bowora at gmail.com> wrote:
>> t
> Hi
>
> I have to matrices t and y below. I want correlation of columns (a,d) (b,e)
> and (c,f). The correlation should be for the first 3 rows of  matrix t
> against matrix y; and then the last 3 i.e a loop function.
>
> I have a code I created below but its giving me an error, surprisingly the
> the individual parts of the code give me the correct answers.
>
> ##########My code is
>
>> runs=2
>> Corrs=matrix(0, nrow=2,3)
>>
>> for (i in 1:2)
> + {
> +  index_start = 3*(i-1)+1  #replace 100 with days in a quater
> +  index_end = 3*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
>
> ####Expected solution
>
>     [,1] [,2]       [,3]
> [1,]    1   -1 -0.9226129
> [2,]    1   -1 -0.8934051
>
> ###individual parts of the loop are
>
>> 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
>
> ####my matrices
>>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
>      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
>
>
> Edward
> UCT
>
> --
> View this message in context: http://r.789695.n4.nabble.com/error-on-my-loop-function-tp3672038p3672038.html
> Sent from the R help mailing list archive at Nabble.com.
>
> ______________________________________________
> R-help at r-project.org mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help