Android Beginner
Android Beginner

Reputation: 486

Access the contents of previous row

df=data.frame(Type=c('Sell','Buy','Sell','Buy'), 
              Date=c('2015-03-24','2014-12-04', '2014-11-07', '2014-05-22'), 
              Quantity=c(2000,600,50,500) ) 

Type        Date    Quantity  Volume
Sell    2015-03-24  2000      1400
Buy     2014-12-04  600       600
Sell    2014-05-22  500       0
Buy     2014-03-28  500       500

Hi, I want to generate values for Volume column based on the following logic

if Type is Sell then previous row [Volume] - current row [Quantity]

if Type is Buy then previous row [Volume] + current row [Quantity]

Upvotes: 0

Views: 56

Answers (1)

Rodrigo
Rodrigo

Reputation: 5119

Try this:

df=data.frame(Type=c('Sell','Buy','Sell','Buy'), 
              Date=c('2015-03-24','2014-12-04', '2014-11-07', '2014-05-22'), 
              Quantity=c(2000,600,50,500) ) 
df

  Type       Date Quantity
1 Sell 2015-03-24     2000
2  Buy 2014-12-04      600
3 Sell 2014-11-07       50
4  Buy 2014-05-22      500

df$Volume <- df$Quantity[nrow(df)]
for (i in (nrow(df)-1):1) {
  if (df$Type[i] == 'Sell') {
    df$Volume[i] <- df$Volume[i+1] - df$Quantity[i]
  } else { # Buy
    df$Volume[i] <- df$Volume[i+1] + df$Quantity[i]
  }
}
df

  Type       Date Quantity Volume
1 Sell 2015-03-24     2000   -950
2  Buy 2014-12-04      600   1050
3 Sell 2014-11-07       50    450
4  Buy 2014-05-22      500    500

Maybe you'll want to order your data.frame first, just to be sure?

Upvotes: 1

Related Questions