Search code examples
rfor-loopmatrixassignscientific-computing

Unable to assign values to 7th column and row in an empty matrix


With R, I write a double loop to assign values to an empty 2d matrix, but it turns out that the 7th column and row were always left blank without an error message.

data2<-matrix(,nrow = 10,ncol = 10)
for(i in seq(0.01,0.1,0.01)){
  for(j in  seq(0.01,0.1,0.01)){
    data2[i*100,j*100]<-i+j
    }}

when I print data2:

 data2
      [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10]
 [1,] 0.02 0.03 0.04 0.05 0.06 0.08   NA 0.09 0.10  0.11
 [2,] 0.03 0.04 0.05 0.06 0.07 0.09   NA 0.10 0.11  0.12
 [3,] 0.04 0.05 0.06 0.07 0.08 0.10   NA 0.11 0.12  0.13
 [4,] 0.05 0.06 0.07 0.08 0.09 0.11   NA 0.12 0.13  0.14
 [5,] 0.06 0.07 0.08 0.09 0.10 0.12   NA 0.13 0.14  0.15
 [6,] 0.08 0.09 0.10 0.11 0.12 0.14   NA 0.15 0.16  0.17
 [7,]   NA   NA   NA   NA   NA   NA   NA   NA   NA    NA
 [8,] 0.09 0.10 0.11 0.12 0.13 0.15   NA 0.16 0.17  0.18
 [9,] 0.10 0.11 0.12 0.13 0.14 0.16   NA 0.17 0.18  0.19
[10,] 0.11 0.12 0.13 0.14 0.15 0.17   NA 0.18 0.19  0.20

When I enter the debug mode and when i=0.01, j=0.07, the weird thing happened:

Browse[2]> i
[1] 0.01
Browse[2]> j
[1] 0.07
Browse[2]> data2[i*100,j*100]
[1] 0.07
Browse[2]> data2[1,7]
[1] NA
Browse[2]> i*100
[1] 1
Browse[2]> j*100
[1] 7

I really get confused about why the 7th column (also, row) cannot be reached by data2[i100,j100], which instead returned the value of data2[1,6]. Can anybody help? I appreciate it. Thanks!


Solution

  • It is because the sequence is a float and there is precision involved with it i.e. it may not be exactly equal to the number 7.

    identical(0.07 * 100, 7)
    #[1] FALSE
    
    (0.07 *100) - 7
    #[1] 8.881784e-16
    

    An option is to round. The index is supposed to be integer and it can be done with round

    for(i in seq(0.01,0.1,0.01)){
      for(j in  seq(0.01,0.1,0.01)){
           data2[round(i*100), round(j*100)] <- i + j
      }}
    

    -output

    data2
    #      [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10]
    # [1,] 0.02 0.03 0.04 0.05 0.06 0.07 0.08 0.09 0.10  0.11
    # [2,] 0.03 0.04 0.05 0.06 0.07 0.08 0.09 0.10 0.11  0.12
    # [3,] 0.04 0.05 0.06 0.07 0.08 0.09 0.10 0.11 0.12  0.13
    # [4,] 0.05 0.06 0.07 0.08 0.09 0.10 0.11 0.12 0.13  0.14
    # [5,] 0.06 0.07 0.08 0.09 0.10 0.11 0.12 0.13 0.14  0.15
    # [6,] 0.07 0.08 0.09 0.10 0.11 0.12 0.13 0.14 0.15  0.16
    # [7,] 0.08 0.09 0.10 0.11 0.12 0.13 0.14 0.15 0.16  0.17
    # [8,] 0.09 0.10 0.11 0.12 0.13 0.14 0.15 0.16 0.17  0.18
    # [9,] 0.10 0.11 0.12 0.13 0.14 0.15 0.16 0.17 0.18  0.19
    #[10,] 0.11 0.12 0.13 0.14 0.15 0.16 0.17 0.18 0.19  0.20
    

    This can be done without a nested for loop and creating an empty matrix as well

    outer(seq(0.01, 0.1, 0.01), seq(0.01, 0.1, 0.01), `+`)