title: R: Confusion with apply() vs for loop
body: <p>I know that I should avoid for-loops, but I'm not exactly sure how to do what I want to do with an apply function.  </p>
  
  <p>Here is a slightly simplified model of what I'm trying to do. So, essentially I have a big matrix of predictors and I want to run a regression using a window of 5 predictors on each side of the indexed predictor (i in the case of a for loop). With a for loop, I can just say something like:</p>
  
  <pre><code>results&lt;-NULL
  window&lt;-5
  for(i in 1:ncol(g))
  {
      first&lt;-i-window #Set window boundaries
      if(first&lt;1){
          1-&gt;first
      }
      last&lt;-i+window-1
      if(last&gt;ncol(g)){
          ncol(g)-&gt;last
      }
      predictors&lt;-g[,first:last]
  
      #Do regression stuff and return some result
      results[i]&lt;-regression stuff
  }
  </code></pre>
  
  <p>Is there a good way to do this with an apply function? My problem is that the vector that apply would be shoving into the function really doesn't matter. All that matters is the index.</p>