Fill missing dates with previous value by group

Viewed 289

Let's say I have the following data.table

library(data.table)
set.seed(123)
df <- as.data.table(data.frame(date = c("2017-01-01", "2017-01-05", "2017-01-08", "2017-01-01", "2017-01-05", "2017-01-08"), 
                 value = rnorm(6),
                 mygroup = rep(LETTERS[1:2], each = 3)))

I want to fill in the missing dates with the 'last' value by group. The closest I have found was this question which shows how to do it without grouping.

all_dates <- seq(from = as.Date("2017-01-01"), 
                   to = as.Date("2017-01-08"), 
                   by = "days")

df[J(all_dates), roll=Inf]

However, I need to do this by group and using the by results in an error

Error in [.data.table(df, J(all_dates), roll = Inf, by = mygroup) : 'by' or 'keyby' is supplied but not j

1 Answers
Related