多变量数据帧差异
Multiple Variable data frame diff
我有一个 data.frame
看起来像这样:
AsofDate PeriodStartDate Price
2007-12-01 2008-01-01 8
2007-12-01 2008-04-01 10
2007-12-01 2008-10-01 16
2007-12-01 2009-01-01 29
2007-12-02 2008-01-01 8
2007-12-02 2008-04-01 10
2007-12-02 2008-10-01 16
2007-12-02 2009-01-01 29
我想计算每天每个相邻季度之间的差异。
所以我想有一种快速的方法来使用不同的时间戳为每个季度的差异创建一个时间序列。
我试过旋转它或使用它 by
但效果不是很好。
在基础 R 中你可以做到
df$diff <- unlist(tapply(df$Price, df$AsofDate, function(x) c(NA,diff(x))))
> df
AsofDate PeriodStartDate Price diff
1 2007-12-01 2008-01-01 8 NA
2 2007-12-01 2008-04-01 10 2
3 2007-12-01 2008-10-01 16 6
4 2007-12-01 2009-01-01 29 13
5 2007-12-02 2008-01-01 8 NA
6 2007-12-02 2008-04-01 10 2
7 2007-12-02 2008-10-01 16 6
8 2007-12-02 2009-01-01 29 13
我有一个 data.frame
看起来像这样:
AsofDate PeriodStartDate Price
2007-12-01 2008-01-01 8
2007-12-01 2008-04-01 10
2007-12-01 2008-10-01 16
2007-12-01 2009-01-01 29
2007-12-02 2008-01-01 8
2007-12-02 2008-04-01 10
2007-12-02 2008-10-01 16
2007-12-02 2009-01-01 29
我想计算每天每个相邻季度之间的差异。
所以我想有一种快速的方法来使用不同的时间戳为每个季度的差异创建一个时间序列。
我试过旋转它或使用它 by
但效果不是很好。
在基础 R 中你可以做到
df$diff <- unlist(tapply(df$Price, df$AsofDate, function(x) c(NA,diff(x))))
> df
AsofDate PeriodStartDate Price diff
1 2007-12-01 2008-01-01 8 NA
2 2007-12-01 2008-04-01 10 2
3 2007-12-01 2008-10-01 16 6
4 2007-12-01 2009-01-01 29 13
5 2007-12-02 2008-01-01 8 NA
6 2007-12-02 2008-04-01 10 2
7 2007-12-02 2008-10-01 16 6
8 2007-12-02 2009-01-01 29 13