Reputation: 1345
I have a data table and want to execute a rollapply
to calculate a rolling average for a particular group. I have:
tt <- data.table(tt, key = c("dt", "id"))
dt id val
1/1/14 a NA
1/2/14 a 3
1/3/14 a 2
1/4/14 a 5
...
2/1/14 a NA
1/1/14 b NA
1/2/14 b 9
1/3/14 b 10
...
2/1/14 b 12
I want to do a three-day rolling average for each id
whenever there is valid data. I tried:
tt[, test := rollapply(val, FUN = mean,
width = 3, na.rm = TRUE), by = list(id))
This gives some odd warnings and then NaNs. Have I done something wrong?
Upvotes: 1
Views: 432
Reputation: 1345
This was resolved within the rollapply
function itself. I needed to add the partial
argument. This worked great:
tt[, test := rollapply(val, FUN = mean, width = 3, na.rm = TRUE,
partial = TRUE), by = list(id)]
Upvotes: 1