R将上个月的值添加为列

时间:2015-05-03 21:24:59

标签: r data.table

我有一个按月显示日期和价格的数据表:

set.seed(128)
dat <- data.table(DATE=c("2014-01-01","2014-02-01","2014-03-01","2014-04-01",
                "2014-05-01","2014-06-01","2014-07-01","2014-08-01",
                "2014-09-01","2014-10-01","2014-11-01","2014-12-01"),
              PRICE=rnorm(n = 12, mean=100, sd=15))
dat

      DATE     PRICE
1: 2014-01-01 108.83590
2: 2014-02-01  67.69042
3: 2014-03-01 122.28905
4: 2014-04-01  93.50617
5: 2014-05-01 109.57878
6: 2014-06-01 128.81537
7: 2014-07-01  82.67295
8: 2014-08-01  68.25281
9: 2014-09-01  82.98265
10: 2014-10-01 124.28960
11: 2014-11-01  84.61275
12: 2014-12-01  93.14938

我想将前几个月的价格作为数据表中的一列添加,因此表格如下所示:

      DATE     PRICE    PRICE_PREV
1: 2014-01-01 108.83590
2: 2014-02-01  67.69042 108.83590
3: 2014-03-01 122.28905 67.69042
...
10: 2014-10-01 124.28960 82.98265
11: 2014-11-01  84.61275 124.28960
12: 2014-12-01  93.14938  84.61275

我如何在R中完成此任务?

2 个答案:

答案 0 :(得分:6)

使用shift v >= 1.9.5 (on GitHub)

中的data.table
dat[, PRICE_PREV := shift(PRICE)]
dat
#           DATE     PRICE PRICE_PREV
#  1: 2014-01-01 108.95158         NA
#  2: 2014-02-01 107.23918  108.95158
#  3: 2014-03-01 124.96608  107.23918
#  4: 2014-04-01  99.61007  124.96608
#  5: 2014-05-01 118.13540   99.61007
#  6: 2014-06-01 108.70528  118.13540
#  7: 2014-07-01  93.12482  108.70528
#  8: 2014-08-01 100.06829   93.12482
#  9: 2014-09-01 103.14932  100.06829
# 10: 2014-10-01 122.66710  103.14932
# 11: 2014-11-01 104.84064  122.66710
# 12: 2014-12-01 113.37610  104.84064

如果你有旧版本(v <1.9.5),你也可以

dat[, PRICE_PREV := c(NA, PRICE[-.N])]

答案 1 :(得分:0)

第一个词没有上个月的已知价格(我假设 - 如果是,你可以用它替换NA)。

以下代码应该可以正常工作。第一行创建一个新向量,第二行将其作为列添加到dat,第三行删除向量(因为它现在在dat中,我们不需要单独使用它)。

PRICE_PREV <- c(NA, dat$PRICE[1:length(dat$PRICE)-1])
dat <- cbind(dat, PRICE_PREV)
rm(PRICE_PREV)