dates = as.Date(c('2000-01-01','2000-02-01','2000-03-01','2000-04-01'))
dt = data.table(date = dates[1:2], value = c(1,2))
> dt
date value
<Date> <num>
1: 2000-01-01 1
2: 2000-02-01 2
> dt[J(dates), on = 'date']
date value
<Date> <num>
1: 2000-01-01 1
2: 2000-02-01 2
3: 2000-03-01 NA
4: 2000-04-01 NA
I want to roll the value forward, but limited to 1 row, ie only to the next data point ('2000-03-01' row). The 'roll' parameter lets me specify the limit in units of the joined 'date' column
> dt[J(dates), on = 'date', roll = 30]
date value
<Date> <num>
1: 2000-01-01 1
2: 2000-02-01 2
3: 2000-03-01 2
4: 2000-04-01 NA
How can I specify to roll forward 1 data point, regardless of how far it is apart in the unit of the joined column?
Something like this?
tmp <- dt[J(dates), on = 'date']
tmp[, test := cumsum(is.na(value)), by = rleid(is.na(value))]
res <- dt[J(dates), on = 'date', roll = Inf][tmp[,test > 1], value := NA][]
# date value
# <Date> <num>
#1: 2000-01-01 1
#2: 2000-02-01 2
#3: 2000-03-01 2
#4: 2000-04-01 NA
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With