1

嗨,在下面的例子中

library(data.table)
library(lubridate)
set.seed(1234)
a = data.table(date=seq(ymd('2001-6-30'),ymd('2003-6-30'),by='weeks'),a=rnorm(105),b=rnorm(105),c=rnorm(105))

我得到的输出有点像

           date           a           b           c
  1: 2001-06-30 -1.20706575  0.16698928  0.41805782
  2: 2001-07-07  0.27742924 -0.89626463 -0.40023524
  3: 2001-07-14  1.08444118  0.16818539  1.49349310
  4: 2001-07-21 -2.34569770  0.35496826 -1.60708094
  5: 2001-07-28  0.42912469 -0.05210512 -0.41575179
 ---                                               
101: 2003-05-31  0.41452353  0.76046236  1.47171869
102: 2003-06-07 -0.47471847  1.84246363  0.44366490
103: 2003-06-14  0.06599349  1.11236284 -0.42172187
104: 2003-06-21 -0.50247778  0.03266396 -0.04000163
105: 2003-06-28 -0.82599859 -1.11444896 -0.49227997

我可以累积它(如果它是回报率)使用

a[,(2:4):=lapply(.SD,function(x) cumprod(x/100+1)),.SDcols=2:4]

并得到

           date         a         b         c
  1: 2001-06-30 0.9879293 1.0016699 1.0041806
  2: 2001-07-07 0.9906701 0.9926923 1.0001615
  3: 2001-07-14 1.0014134 0.9943618 1.0150988
  4: 2001-07-21 0.9779233 0.9978915 0.9987854
  5: 2001-07-28 0.9821198 0.9973716 0.9946329
 ---                                         
101: 2003-05-31 0.8540733 1.0838999 1.1223825
102: 2003-06-07 0.8500188 1.1038704 1.1273621
103: 2003-06-14 0.8505798 1.1161495 1.1226078
104: 2003-06-21 0.8463058 1.1165140 1.1221587
105: 2003-06-28 0.8393153 1.1040711 1.1166346

我的问题是,如果我有输出并想回到原来的回报率,我该怎么办?

b=(a[2:105,2:4,with=F]/a[1:104,2:4,with=F]-1)*100

其次是合并似乎很笨拙,我很难弄清楚合并操作。

谢谢

4

1 回答 1

2

这与 cumprod 几乎相同:

a[,(2:4):=lapply(.SD,function(x) c(NA,(tail(x,-1)/head(x,-1)-1)*100)),.SDcols=2:4]
于 2013-06-05T08:40:50.380 回答