my data.table (package: data.table
) looks as follows:
set.seed(1)
data <- data.table(time =c(1:3,1:4),groups = c(rep(c("b","a"),c(3,4))), value = rnorm(7))
groups time value
1: b 1 -0.6264538
2: b 2 0.1836433
3: b 3 -0.8356286
4: a 1 1.5952808
5: a 2 0.3295078
6: a 3 -0.8204684
7: a 4 0.4874291
I want to be able to lag the value column by more than one value. Below is an example of the output if value is lagged by 2 (however the lag amount should be set arbitrarily):
groups time value lag.value
1 a 1 1.5952808 NA
2 a 2 0.3295078 NA
3 a 3 -0.8204684 1.5952808
4 a 4 0.4874291 0.3295078
5 b 1 -0.6264538 NA
6 b 2 0.1836433 NA
7 b 3 -0.8356286 -0.6264538
please advise
EDIT: This question was posted for the purpose of elaborating on an answer posted here