title: Populating a 4-D array in r
body: <p>I'm trying to load data into a 4-D array and having some trouble. Here is the structure of the data and the code I'm using:</p>
  
  <pre><code>  X   CREPid Year Survey Habitat julien Clouds Precip Noise Wind y species
  1 1 19990008 2012      1       1    151      1      1     1    1 1    AMGO
  2 2 19990027 2012      1       2    173      3      1     1    1 1    AMGO
  3 3 19990031 2012      1       1    139      1      1     2    3 0    AMGO
  4 4 19990033 2012      1       1    181      3      1     1    1 1    AMGO
  5 5 19990034 2012      1       1    181      2      1     2    2 1    AMGO
  6 6 19990037 2012      1       1    139      1      1     1    1 1    AMGO
  
  # Format data in a spreadsheet format into a 4d array
  # Determine required dimensions of 4d array
  nsite &lt;- length(unique(df$site))    # Number of sites (242)
  nvisit &lt;- length(unique(df$visit))  # Number of surveys or visits(3 per year)
  nyear &lt;- length(unique(df$year))    # Number of years(4 years)
  nspec &lt;- length(unique(df$species)) # Number of species (46 species)
  
  # Prepare array and pre-fill array with NAs
  BigArray2 &lt;- array(NA, dim = c(nsite, nvisit, nyear, nspec))
  
  # Fill array with the detection/nondetection data
  # Loop over all rows in the spreadsheet data and fill them in 
  #   at the right place in the 4d array
  
  for(i in 1:nrow(CREPallOccFinal)){
  BigArray2[CREPallOccFinal$CREPid[i], CREPallOccFinal$Survey[i], CREPallOccFinal$Year[i], CREPallOccFinal$species[i]]&lt;- CREPallOccFinal$y[i]}
  </code></pre>
  
  <p>However, every time I run the code, I get this error message:</p>
  
  <blockquote>
    <p>Error in <code>[&lt;-</code>(<code>*tmp*</code>, CREPallOccFinal$CREPid[i], CREPallOccFinal$Survey[i],  : 
      subscript out of bounds</p>
  </blockquote>
  
  <p>I cant figure out the problem, any help would be much appreciated.</p>