访问上一行的内容

时间:2017-03-10 03:16:01

标签: r

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

嗨,我想基于以下逻辑

为Volume列生成值

如果Type为Sell,则前一行[Volume] - 当前行[Quantity]

如果Type为Buy,则前一行[Volume] +当前行[Quantity]

1 个答案:

答案 0 :(得分:1)

试试这个:

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

也许您首先要订购data.frame,以确定?