Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

R data.table rolling join with limit window in number of data points

Tags:

join

r

data.table

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?

like image 847
jf328 Avatar asked Jan 23 '26 16:01

jf328


1 Answers

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
like image 187
Roland Avatar answered Jan 25 '26 09:01

Roland



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!