title: R: combine rows of a matrix by group
body: <p>I am attempting to reformat the data set <code>my.data</code> to obtain the output shown below the <code>my.data2</code> statement.  Specifically, I want to put the last 4 columns of <code>my.data</code> on one line per <code>record.id</code>, where the last four
  columns of <code>my.data</code> will occupy columns 2-5 of the new data matrix if <code>group=1</code> and columns 6-9 if <code>group=2</code>.</p>
  
  <p>I wrote the cumbersome code below, but the double for-loop is causing an error that I simply cannot locate.
  Even if the double for-loop worked, I suspect there is a much more efficient way of accomplishing the
  same thing - (maybe <code>reshape</code>?)</p>
  
  <p>Thank you for any help correcting the double for-loop or with more efficient code.</p>
  
  <pre><code>my.data &lt;-  "record.id group s1 s2 s3 s4
      1  1      2      0      1      3
      1  2      0      0      0     12
      2  1      0      0      0      0
      3  1     10      0      0      0
      4  1      1      0      0      0
      4  2      0      0      0      0
      8  2      0      2      2      0
      9  1      0      0      0      0
      9  2      0      0      0      0"    
  
  my.data2 &lt;- read.table(textConnection(my.data), header=T)
  
  # desired output
  #
  # 1     2      0      1      3      0      0      0     12
  # 2     0      0      0      0      0      0      0      0
  # 3    10      0      0      0      0      0      0      0
  # 4     1      0      0      0      0      0      0      0
  # 8     0      0      0      0      0      2      2      0
  # 9     0      0      0      0      0      0      0      0
  </code></pre>
  
  <p>Code:</p>
  
  <pre><code>dat_sorted &lt;- sort(unique(my.data2[,1]))
  my.seq &lt;- match(my.data2[,1],dat_sorted)
  
  my.data3 &lt;- cbind(my.seq, my.data2)
  
  group.min &lt;- tapply(my.data3$group, my.data3$my.seq, min)
  group.max &lt;- tapply(my.data3$group, my.data3$my.seq, max)
  
  # my.min &lt;- group.min[my.data3[,1]]
  # my.max &lt;- group.max[my.data3[,1]]
  
  my.records &lt;- matrix(0, nrow=length(unique(my.data3$record.id)), ncol=9)
  
  x &lt;- 1
  
  for(i in 1:max(my.data3$my.seq)) {
  
     for(j in group.min[i]:group.max[i]) {
  
        if(my.data3[x,1] == i) my.records[i,1]   = i
  
        # the two lines below seem to be causing an error
        if((my.data3[x,1] == i) &amp; (my.data3[x,3] == 1)) (my.records[i,2:5] = my.data3[x,4:7])
        if((my.data3[x,1] == i) &amp; (my.data3[x,3] == 2)) (my.records[i,6:9] = my.data3[x,4:7])
  
        x &lt;- x + 1
  
     }
  }
  </code></pre>