2

I am simulating a correlation matrix, where the 60 variables correlate in the following way:

  • more highly (0.6) for every two variables (1-2, 3-4... 59-60)
  • moderate (0.3) for every group of 12 variables (1-12,13-24...)

    mc <- matrix(0,60,60)   
    diag(mc) <- 1
    
    for (c in seq(1,59,2)){    # every pair of variables in order are given 0.6 correlation
    mc[c,c+1] <- 0.6
    mc[c+1,c] <- 0.6
    }
    
    
    for (n in seq(1,51,10)){        # every group of 12 are given correlation of 0.3 
      for (w in seq(12,60,12)){     # these are variables 11-12, 21-22 and such.
        mc[n:n+1,c(n+2,w)] <- 0.2
        mc[c(n+2,w),n:n+1] <- 0.2
      }
    }
    
    for (m in seq(3,9,2)){               # every group of 12 are given correlation of 0.3
       for (w in seq(12,60,12)){          # these variables are the rest.
         mc[m:m+1,c(1:m-1,m+2:w)] <- 0.2
         mc[c(1:m-1,m+2:w),m:m+1] <- 0.2
       }
    }
    

The first loop works well, but not the second and third ones. I get this error message:

Error in `[<-`(`*tmp*`, m:m + 1, c(1:m - 1, m + 2:w), value = 0.2) : 
  subscript out of bounds

Error in `[<-`(`*tmp*`, m:m + 1, c(1:m - 1, m + 2:w), value = 0.2) : 
  subscript out of bounds

I would really appreciate any hints, since I don't see the loop commands get to exceed the matrix dimensions. Thanks a lot in advance!

Gina Zetkin
  • 333
  • 1
  • 5
  • 12
  • try putting `cat()` or `print()` statements in your code to see what's going on, or use `options(error=recover)` to have R dump you into a browser when an error occurs ... – Ben Bolker Jan 14 '14 at 13:35
  • 3
    Note that `:` takes precedence over `+`. E.g., `n:n+1` is the same as `n+1`. I guess you want `n:(n+1)`. – Roland Jan 14 '14 at 13:37
  • @Roland "Extra parentheses FTW" :-) – Carl Witthoft Jan 14 '14 at 14:00
  • 1
    For googlers: several subscript out of bounds questions on SO: http://stackoverflow.com/questions/20318568/r-error-subscript-out-of-bounds http://stackoverflow.com/questions/11831786/error-in-tmpj-subscript-out-of-bounds http://stackoverflow.com/questions/14333525/error-in-tmpk-subscript-out-of-bounds-in-r – isomorphismes Feb 06 '14 at 19:10

1 Answers1

3

Note that : takes precedence over +. E.g., n:n+1 is the same as n+1. I guess you want n:(n+1).

The maximal value of w is 60:

w <- 60
m <- 1
m+2:w
#[1]  3  4  5  6  7  8  9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50
#[49] 51 52 53 54 55 56 57 58 59 60 61

And 61 is out of bounds. You need to add a lot of parentheses.

Roland
  • 127,288
  • 10
  • 191
  • 288