I have two matrices I want to perform a loop on. My problem is I am looping for one colomn and do not know how to include the other column, hence my incorrect results. My codes are as below:
t=as.matrix(b)
y=as.matrix(a)
t
a b
[1,] 1 10
[2,] NA 9
[3,] 3 NA
[4,] 4 7
[5,] 5 6
[6,] 3 4
y
c d
[1,] 3 12
[2,] NA 11
[3,] 5 NA
[4,] 6 9
[5,] 7 8
[6,] 3 12
turn
[,1] [,2]
[1,] 0 0
[2,] 0 0
Code:
n=3 #number to consider at a time
runs=2 #total data points divided by 60 to the nearest whole number
turn=matrix(0, nrow=runs,2)
TR = y/t
for (i in 1: runs){
index_start=3*(i-1)+1
index_end= 3*i
turn[i]=mean( TR[index_start:index_end],na.rm=TRUE)
}
turn
[,1] [,2]
[1,] 2.333333 0
[2,] 1.300000 0
The turn output has given correct results for the first column but, as expected, incorrect results for the second column. How do I adjust my loop function? Thank you in advance.
Look at the line
If you only give a single number in the index of a matrix, it will work out the position by counting down the first column, then down the second, and so on.
So
turn[1]refers to the element in the top left corner of the matrixturn, andturn[2]refers to the bottom left corner.In your loop,
itakes the values1:runs, andrunsis 2, so you only assign things to the first two elements ofturn.