Add rows to missing time series months

Hello,

I want to using monthly time series to forecast a volume.
However, the volume in March and April were both zero and they are completely absent from the series.
So, I want to add two rows to my series, one for march and one for April with volume of zero for each of them. I aggregated my data from daily to monthly and I have something like this:

reprex1 <- tibble(
  month.yeard = yearmonth(c('2020-03','2020-06')),
  vol = c(20L, 30L) 
  add_row('2020-04', 20L, .after = 3)
)

reprex1

I would like to add 2020 Apr and 2020 May to my series and give them a volume of 0 each.
What is the most efficient way to do this? I tried to use add_row. Something is wrong.

Please help!

Hi dsgeek,
You were on the right track, and add_row can only add rows to completed tsibbles via piping and not during construction. In addition, you have to make sure that
you're adding the same data types.

library("tidyverse")
library("tsibble")

reprex1 <- tibble(
  month.yeard = yearmonth(c('2020-03','2020-06')),
  vol = c(20L, 30L)) %>%
  add_row(month.yeard = yearmonth(c('2020-04', '2020-05')), vol = c(0L, 0L),
    .after = 3)

reprex1
#> # A tibble: 4 x 2
#>   month.yeard   vol
#>         <mth> <int>
#> 1    2020 Mar    20
#> 2    2020 Jun    30
#> 3    2020 Apr     0
#> 4    2020 May     0

Created on 2020-07-13 by the reprex package (v0.3.0)

The code below will fill all missing months without having to explicitly know where the gaps are:

library(tidyverse)
library(tsibble)

reprex1 <- tibble(
  month.yeard = yearmonth(c('2020-03','2020-06')),
  vol = c(20L, 30L)
)

r = range(reprex1$month.yeard, na.rm=TRUE)
all.months = tibble(month.yeard = seq(r[1], r[2], 1))

reprex1 %>% 
  full_join(all.months) %>% 
  replace_na(list(vol=0))
#> Joining, by = "month.yeard"
#> # A tibble: 4 x 2
#>   month.yeard   vol
#>         <mth> <dbl>
#> 1    2020 Mar    20
#> 2    2020 Jun    30
#> 3    2020 Apr     0
#> 4    2020 May     0

Created on 2020-07-13 by the reprex package (v0.3.0)

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.

Thank you Joel. This is awesome. I did it using

reprex1 %>% add_row(tibble_row(month.yeard = yearmonth('2020-04'), vol = 0L), .after = 1)

Then added added another row. Seems tedious. Your method is far more superior. Thank you!