1

I have a data frame of values

   Demand    Supply 
1  722.3846    750        
2  774.3762    800   
3  885.1103    900   
4  120.4484    100   
5  175.2068    150  
6  221.1865    250   
7  275.1496    350   
8  320.3225    330   
9  622.3530    650   
10 663.0514    680   
11 683.0443    690   
12 694.6459    700   

I would like to calculate the balance(Demand - Supply) & Imbalance( Demand -Supply - Prev(Bal))

OutPut Should like:

    Demand    Supply     Balance                  Imbalance
  1  722.3846    750    -27.6154              0(722.3846-750-(-27.6154)
  2  774.3762    800     0(PrevMonthImbal)    -25.6238(774.3762-800-0)
  3  885.1103    900    -25.6238               ............
  4  120.4484    100   
  5  175.2068    150  
  6  221.1865    250   
  7  275.1496    350   
  8  320.3225    330   
  9  622.3530    650   
  10 663.0514    680   
  11 683.0443    690   
  12 694.6459    700   

How can I do this in R

Adury
  • 29
  • 4
  • I like to use [this `data.table` solution using `shift`](http://stackoverflow.com/q/14689424/5977215) for calculations like yours. – SymbolixAU Apr 24 '17 at 04:17

1 Answers1

1

We can use data.table

library(data.table)
setDT(df2)[, Balance := Demand - Supply][,  Imbalance := Balance - shift(Balance)]
akrun
  • 874,273
  • 37
  • 540
  • 662