title: R calculating average purchase price
body: <p>I just started learning R (really, only a day of experience) and I'm currently trying to migrate an SQL code to R just to see how they compare.</p>
  
  <p>One of the use cases is calculating average stock purchase price. Now in my data I have transactions with negative and positive volume, and only + volume is used to calculate avg. On the other hand, the average purchase price is needed at rows with - volume, as that is later used to calculate profit/loss of that sales transaction.</p>
  
  <p>A sample data could be constructed like this:</p>
  
  <pre><code>df = data.frame(matrix(rnorm(20)*10, nrow=10))
  df$X3 &lt;- df$X2 * df$X2
  </code></pre>
  
  <p>then I have a function which calulates avg:</p>
  
  <pre><code>avgPurchasePrice &lt;- function(volume, eurPrice){
    price &lt;- vector(mode="numeric", length=length(volume))
    s=0
    t=0
    for(i in 1:length(volume)){
      if(volume[i]&gt;0){
        price[i] &lt;- volume[i]*eurPrice[i]+t;
        volume[i]&lt;-volume[i]+s;
        s &lt;- volume[i];
        t &lt;- price[i];
      } else {
        volume[i] &lt;- s;
        price[i] &lt;-t;
      }
      volume[i]=price[i]/volume[i];
    }
    volume
  }
  </code></pre>
  
  <p>and average is calculated as </p>
  
  <pre><code>df$avgPrice &lt;- avgPurchasePrice(df$X1,df$X3)
  </code></pre>
  
  <p>Question: is this approach OK? I don't know R and there might be better ways / patterns to implement this, as this approach seems very "traditional"</p>
  
  <p>Edit:</p>
  
  <p>In words I think it should be: for each positive volume, calculate average (buy) price as ratio of total price over total volume; for negative volume use the last value without changing it</p>
  
  <p>I've looked into dplyr and came up with this (which only works on my data file)</p>
  
  <p><code>stock %&gt;% group_by(FINANCIAL_INSTRUMENT) %&gt;% mutate(                                                 cumPrice=cumsum(vol=ifelse(VOLUME&gt;0,VOLUME,0L)*PricE),                                                cumVol=cumsum(ifelse(VOLUME&gt;0L,VOLUME,0L)),
                                                       cumPrice/cumVol)</code></p>