滞后差异 [英] Lagged differences

查看:97
本文介绍了滞后差异的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

样本数据:

Date <- as.Date(c('1-01-2008','2-01-2008', '3-01-2008','4-01-2008', '5-01-2008', '1-01-2008','2-01-2008', '3-01-2008','4-01-2008', '5-01-2008'), format = "%m-%d-%Y") 
Country <- c('US', 'US','US','US', 'US', 'JP', 'JP', 'JP', 'JP', 'JP') 
Category <- c('Apple', 'Apple', 'Apple', 'Apple', 'Apple', 'Apple', 'Apple', 'Apple', 'Apple', 'Apple') 
Value <- c(runif(10, -0.5, 10))
df <- data.frame(Date, Country, Category, Value)

我正在使用以下代码来计算国家/地区"和类别"中Value的滞后增长率:

I am using the following piece to calculate the lagged growth rate of Value within Country and within Category:

df <- ddply(df, .(Country, Category), transform,
                 Growth6m=c(NA, NA, NA, exp(diff(log(Value), lag = 3))-1))

现在,我正试图使差异滞后,而不是增长率.对于第一次延迟(即从上一行中减去值),这种方法效果很好,如下所示:

Now I am trying to get lagged difference rather than growth rate. This worked fine for the first lag (i.e. subtracting value from the previous row) like this:

 df <- ddply(df, .(Country, Category), transform,
          Growth1m=c(NA, diff(Value))) 

但是当我引入更高阶的滞后时(例如,从第三行中减去第一行),我得到如下错误:参数表示不同的行数:157、158".我尝试与NA一起玩,但无济于事.

but when I introduce higher order lags (ex. subtracting the first row from the third row), I get the error such as: "arguments imply differing number of rows: 157, 158". I tried playing around with the NA's but to no avail.

示例数据

推荐答案

使用dplyr很容易

library(dplyr)
df %>%
  group_by(Country, Category) %>%
  mutate(
    deltaLag1 = Value - lag(Value, 1),
    deltaLag2 = Value - lag(Value, 2)
  )

这篇关于滞后差异的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆