Home > Net >  R - transform time series data frame
R - transform time series data frame

Time:08-11

I have a dataset with features (f) for different stocks (S) like this:

year S1_f1 S1_f2 S2_f1 S2_f2 Sn_f1 Sn_f2
2010   0.1  0.12   0.2  0.22   0.3  0.32
2011   0.4  0.42   0.5  0.52   0.6  0.62
2012   0.7  0.72   0.8  0.82   0.9  0.92
n        n     n     n     n     n     n

and so on... (example values).

Now I want to restructure my df, so that features from 1 year in the past (p) are shifted one year to the future (f). Like this:

year S1_f1_p S1_f2_f S1_f2_p S1_f2_f S2_f1_p S2_f1_f S2_f2_p S2_f2_f ... Sn_fn_f
2011     0.1     0.4    0.12    0.42     0.2     0.5    0.22    0.52           n
2012     0.4     0.7    0.42    0.72     0.5     0.8    0.52    0.82           n
2013     0.7       n    0.72       n     0.8       n    0.82       n           n
n          n       n       n       n       n       n       n       n           n

Is there an elegant way to achieve this?

CodePudding user response:

flag in the collapse package can handle vector lags:

cbind(DF[1], flag(DF[-1], 0:-1))
##   year S1_f1 F1.S1_f1 S1_f2 F1.S1_f2 S2_f1 F1.S2_f1 S2_f2 F1.S2_f2 Sn_f1 F1.Sn_f1 Sn_f2 F1.Sn_f2
## 1 2010   0.1      0.4  0.12     0.42   0.2      0.5  0.22     0.52   0.3      0.6  0.32     0.62
## 2 2011   0.4      0.7  0.42     0.72   0.5      0.8  0.52     0.82   0.6      0.9  0.62     0.92
## 3 2012   0.7       NA  0.72       NA   0.8       NA  0.82       NA   0.9       NA  0.92       NA
  •  Tags:  
  • r
  • Related