title: faster way to do this table transformation in R
body: <p>I have a simple table of stock prices, let's call it "price," with tickers along the top and dates along the side.</p>
  
  <p>I want to create a new table, "price_norm," which divides every price by the first one. So for example, the first column might look like:</p>
  
  <pre><code>price     price_norm
  20.00     1.000
  21.00     1.050
  21.00     1.050
  20.00     1.000
  20.50     1.025
  </code></pre>
  
  <p>...etc</p>
  
  <p>The wrinkle is that some stocks don't have pricing all the way back to the first date, so their column in "price" begins with a string of NAs -- in that case they should be divided by the first non-NA value, not the value in the first row.</p>
  
  <p>There may also be a few stocks with no price at all, where every value is NA; in this case the corresponding column in price_norm should be all NA too.</p>
  
  <p>I have done this in a way that works but very slowly -- 30 seconds or more to process. I'm looking for a more efficient way:</p>
  
  <pre><code>price_norm &lt;- price
  
  nonNAIndex &lt;- function(z) {
    min(which(!is.na(z)))
  }
  
  for( j in colnames(price) ) {
  
    if(!is.na(price[nrow(price),j])) {  
  
      k &lt;- nonNAIndex(price[,j])
  
      for( i in k:nrow(price) ) {
        price_norm[i,j] &lt;- ( price[i,j] / price[k,j] ) 
      }
    }
  }
  </code></pre>