title: Creating a 3D matrix with R?
body: <p>I'm trying to build a 3D matrix by looping variables in a large data set (please see the 'head' of the data below). Specifically, I need to create a matrix with as many rows as the maximum number of 'LastFixes', as many columns as there are subjects (Sub = 36) and as many pages as there are conditions (i.e., 8), and I want to assign 1s in a row from the start of FixStart up until the end of a FixEnd, and 0s from end of a FixEnd until the start of FixStart and so on and so forth. So for example, for the first rows of the data, I need to have 1s in the first 165 rows of the matrix and then 0s from row# 166 until 330. My R code works, but strangely, I get numbers other than 0s and 1s in the matrix! Below you can see the 'head' and as well as the R code. I would be grateful if anyone could help me fix this problem. Many thanks</p>
  
  <pre><code>enter code here
  
  head (data)
  
    Sub Item Condition FixStart FixEnd
  1   1    4         7        1    165
  2   1    4         7      331    600
  3   1    4         7      623   1180
  4   1    4         7     1202   1487
  5   1    4         7     1511   1561
  6   1    4         7     1696   2466
  
  
  lastFix &lt;- max(data$FixEnd)
  
  
  datamatrix&lt;-array(0,dim=c(lastFix,36,8))
  
  for (i in 1:length(data$Sub)){ 
    n &lt;- data[i,1]
    if (data[i,3] == "1"){
      for (j in data[i,4]:data[i,5]){
        datamatrix[j,n,1] &lt;- datamatrix[j,n,1]+1
      }
    }else 
    if (data[i,3] == "2"){
      for (j in data[i,4]:data[i,5]){
        datamatrix[j,n,2] &lt;- datamatrix[j,n,2]+1
      }
    }else 
    if (data[i,3] == "3"){
      for (j in data[i,4]:data[i,5]){
        datamatrix[j,n,3] &lt;- datamatrix[j,n,3]+1
      }
    }else
    if (data[i,3] == "4"){
      for (j in data[i,4]:data[i,5]){
        datamatrix[j,n,4] &lt;- datamatrix[j,n,4]+1
      }
    }else
    if (data[i,3] == "5"){
      for (j in data[i,4]:data[i,5]){
        datamatrix[j,n,5] &lt;- datamatrix[j,n,5]+1
      }
    }else
    if (data[i,3] == "6"){
      for (j in data[i,4]:data[i,5]){
        datamatrix[j,n,6] &lt;- datamatrix[j,n,6]+1
      }
    }else
    if (data[i,3] == "7"){
      for (j in data[i,4]:data[i,5]){
        datamatrix[j,n,7] &lt;- datamatrix[j,n,7]+1
      }
    }else
    if (data[i,3] == "8"){
      for(j in data[i,4]:data[i,5]){
        datamatrix[j,n,8] &lt;- datamatrix[j,n,8]+1
      }
    }
  }
  </code></pre>