Fastest way for filling-in missing dates for data.table

后端 未结 3 1505
攒了一身酷
攒了一身酷 2020-12-05 05:58

I am loading a data.table from CSV file that has date, orders, amount etc. fields.

The input file occasionally does not have data for all dates. For exa

3条回答
  •  囚心锁ツ
    2020-12-05 06:31

    Not sure if it's the fastest, but it'll work if there are no NAs in the data:

    # just in case these aren't Dates. 
    NADayWiseOrders$date <- as.Date(NADayWiseOrders$date)
    # all desired dates.
    alldates <- data.table(date=seq.Date(min(NADayWiseOrders$date), max(NADayWiseOrders$date), by="day"))
    # merge
    dt <- merge(NADayWiseOrders, alldates, by="date", all=TRUE)
    # now carry forward last observation (alternatively, set NA's to 0)
    require(xts)
    na.locf(dt)
    

提交回复
热议问题