title: How to have a result by group when group_by doesn't apply. Weighted averages for stocks
body: <p>I want to update the  weighted averages of my stocks price as buy and sell them.<br>
  I found a partial solution (looking though the stack overflow: <a href="https://stackoverflow.com/questions/49312147/using-shift-and-data-table-to-update-the-value-of-an-inventory">Using shift and data table to update the value of an inventory</a>), but it doesn't group by share.
  My data looks like this:</p>
  
  <pre><code>
  library(data.table)
  
  ledger &lt;-data.table(
    Share = c(rep("b",3), rep("x",2)),
    Prc = c(10,20,15, 35,40),
    Qty= c(300,-50,100, 50,-10),
    Op =c("Purchase", "Sale", "Purchase", "Purchase", "Sale")
  
  
  )
  </code></pre>
  
  <p>What I came up so far:</p>
  
  <pre><code>ledger&lt;-ledger %&gt;%group_by(Share)%&gt;%
    mutate(Stock = cumsum(Qty))%&gt;%
    group_by(Share)%&gt;%
    mutate(id =row_number())%&gt;%
    mutate(AvgPrice =ifelse( id ==1, Prc, NA_real_))
  
  ledger&lt;-as.data.table(ledger)
  
  ledger[, Stock := cumsum(Qty)]  # compute Stock value
  ledger[, `:=` ( id = .I, AvgPrice = NA_real_ ) ] # add id and AvgPrice columns
  ledger[ 1, AvgPrice := Prc] # compute AvgPrice for first row
  
  # work with remaining rows and find the AvgPrice
  ledger[ ledger[, .I[-1]], AvgPrice := {
    if( Op == "Sale" ){   
      ledger[ .I-1, AvgPrice ]
    } else {
      round( ( ( Qty * Prc ) + ledger[ .I-1, AvgPrice * Stock ] ) /
               ( Qty + ledger[ .I-1, Stock]) ,
             digits = 2 )
    }
  }, by = id ]
  
  ledger[, id := NULL ]  # remove id column
  </code></pre>
  
  <p>The problem is I would like it restart when "Share"changes from b to x. As it would do with a group_by function.</p>
  
  <p>I appreciate any help.</p>