title: How can I loop a data matrix in R?
body: <p>I am trying to loop a data matrix for each separate ID tag, “1”, “2” and “3” (see my data at the bottom). Ultimately I am doing this to transform the X and Y coordinates into a timeseries with the ts() function, but first i need to build a loop into the function that returns a timeseries for each separate ID. The looping itself works perfectly fine when I use the following code for a dataframe:</p>
  
  <p><code>for(i in 1:3){
      print(na.omit(xyframe[ID==i,]))
      }</code></p>
  
  <p>Returning the following output: </p>
  
  <pre><code> Timestamp X Y ID  
   1. 0 -34.012 3.406 1  
   2. 100 -33.995 3.415 1  
   3. 200 -33.994 3.427 1
  
   Timestamp       X     Y ID  
   4.          0 -34.093 3.476 2  
   5.        100 -34.145 3.492 2  
   6.        200 -34.195 3.506 2  
  
     Timestamp       X     Y ID  
   7.         0 -34.289 3.522 3  
   8.       100 -34.300 3.520 3  
   9.       200 -34.303 3.517 3  
  </code></pre>
  
  <p>Yet, when I want to produce a loop in a matrix with the same code:</p>
  
  <p><code>for(i in 1:3){
      print(na.omit(xymatrix[ID==i,])
      }</code></p>
  
  <p>It returns the following error:</p>
  
  <pre><code>Error in print(na.omit(xymatrix[ID == i, ]) : 
    (subscript) logical subscript too long
  </code></pre>
  
  <p>Why does it not work to loop the ID through a matrix while it does work for the dataframe and how would I be able to fix it? 
  Furthermore did I read that looping requires much more computational strength then doing the same thing vector based, would there be a way to do this vector based? </p>
  
  <p><em><strong>The data (simplification of the real data):</em></strong>  </p>
  
  <pre><code> Timestamp X Y ID  
   1.   0 -34.012 3.406 1  
   2. 100 -33.995 3.415 1  
   3. 200 -33.994 3.427 1  
   4.   0 -34.093 3.476 2  
   5. 100 -34.145 3.492 2  
   6. 200 -34.195 3.506 2  
   7.   0 -34.289 3.522 3  
   8. 100 -34.300 3.520 3  
   9. 200 -34.303 3.517 3 
  </code></pre>