r - How to lag data table value by more than one -
say have info table. can create column of lagged values:
>x date id val valpr 1/4/14 1 2 1/3/14 2 3 1/2/14 3 4 1/1/14 4 na 1/4/14 b 10 20 1/3/14 b 20 30 1/2/14 b 30 40 1/1/14 b 40 na
using:
setdt(x)[, valpr := c(val[-1], na), = "id"]
is there way similar lag more 1 period? 3 example?
it produce this:
>x date id val valpr 1/4/14 1 4 1/3/14 2 na 1/2/14 3 na 1/1/14 4 na 1/4/14 b 10 40 1/3/14 b 20 na 1/2/14 b 30 na 1/1/14 b 40 na
you alternatively following. lead
function in dplyr
.
setdt(mydf)[, valpr2 := lead(val, 3), = "id"] # date id val valpr valpr2 #1: 1/4/14 1 2 4 #2: 1/3/14 2 3 na #3: 1/2/14 3 4 na #4: 1/1/14 4 na na #5: 1/4/14 b 10 20 40 #6: 1/3/14 b 20 30 na #7: 1/2/14 b 30 40 na #8: 1/1/14 b 40 na na
data
mydf <- structure(list(date = structure(c(4l, 3l, 2l, 1l, 4l, 3l, 2l, 1l), .label = c("1/1/14", "1/2/14", "1/3/14", "1/4/14"), class = "factor"), id = structure(c(1l, 1l, 1l, 1l, 2l, 2l, 2l, 2l), .label = c("a", "b"), class = "factor"), val = c(1l, 2l, 3l, 4l, 10l, 20l, 30l, 40l), valpr = c(2l, 3l, 4l, na, 20l, 30l, 40l, na)), .names = c("date", "id", "val", "valpr"), class = "data.frame", row.names = c(na, -8l))
r data.table
No comments:
Post a Comment