数据框中的累计值随时间的变化

时间:2017-05-12 13:54:20

标签: r dataframe

我有以下数据框;

Date <- as.Date(c('2006-08-23', '2006-08-30', '2006-09-06', '2006-09-13', '2006-09-20'))
order <- c("buy", "buy", "sell", "buy", "buy")
cost <- c(10, 15, 12, 13, 8)
df <- data.frame(Date, order, cost)
df
             Date order cost
     1 2006-08-23   buy   10
     2 2006-08-30   buy   15
     3 2006-09-06  sell   12
     4 2006-09-13   buy   13
     5 2006-09-20   buy    8

如何通过考虑日期和订单列来汇总成本列,并在像这样的新数据框中获取新的余额列?

             Date order cost balance
     1 2006-08-23   buy   10      10
     2 2006-08-30   buy   15      25
     3 2006-09-06  sell   12      13
     4 2006-09-13   buy   13      26
     5 2006-09-20   buy    8      34

1 个答案:

答案 0 :(得分:2)

假设您有一个已排序的DF,&#34;成本&#34;是一个不明智的标签,因为我们必须生成一个标志,以显示基于买/卖旗帜的实际成本。

df$cost[df$order == 'sell'] <- -df$cost[df$order == 'sell']
然后

余额为cumsum(df$cost)