计算R中的月/季/年增量

时间:2015-02-17 18:49:22

标签: r dplyr time-series

下面是数据框的样子,我怎样才能创建右边的列,总结月份差异,季度差异以及R的年度差异?感谢。

enter image description here

1 个答案:

答案 0 :(得分:1)

试试这个:

# test data
DF <- data.frame(Date = c(paste0(month.abb, 2015), paste0(month.abb, 2016)), 
                 Aggressive = seq(24)^2, Moderate = seq(24)^2)

Diff <- function(x, k) x - c(rep(NA, k), head(x, -k))
transform(DF, Aggressive_Mon = Diff(Aggressive, 1),
                Moderate_Mon = Diff(Moderate, 1),
                Aggressive_Qtr = Diff(Aggressive, 3),
                Moderate_Qtr = Diff(Moderate, 3),
                Aggressive_Yr = Diff(Aggressive, 12),
                Moderate_Yr = Diff(Moderate, 12))

下次请不要使用图片来显示数据,而是显示dput(DF)的输出。