Filter just month in filter(year(Month)) tsibble

I would like to filter the month of July , in order to get every July across all years
how can I modify below code to achieve it?

library("fpp3")
us_retail_employment <- us_employment %>%
  filter(year(Month) >= 1990, Title == "Retail Trade") %>%
  select(-Series_ID)

A tsibble: 357 x 3 [1M]
Month Title Employed

1990 Jan Retail Trade 13256.
1990 Feb Retail Trade 12966.

You need to filter on Month like this:

library(fpp3)
us_employment %>%
  filter(Title == "Retail Trade") %>%
  filter(month(Month) == 7)
#> # A tsibble: 81 x 4 [1M]
#> # Key:       Series_ID [1]
#>       Month Series_ID     Title        Employed
#>       <mth> <chr>         <chr>           <dbl>
#>  1 1939 Jul CEU4200000001 Retail Trade    3100 
#>  2 1940 Jul CEU4200000001 Retail Trade    3251.
#>  3 1941 Jul CEU4200000001 Retail Trade    3523.
#>  4 1942 Jul CEU4200000001 Retail Trade    3416.
#>  5 1943 Jul CEU4200000001 Retail Trade    3412.
#>  6 1944 Jul CEU4200000001 Retail Trade    3443.
#>  7 1945 Jul CEU4200000001 Retail Trade    3509.
#>  8 1946 Jul CEU4200000001 Retail Trade    4048.
#>  9 1947 Jul CEU4200000001 Retail Trade    4314.
#> 10 1948 Jul CEU4200000001 Retail Trade    4450.
#> # … with 71 more rows

Created on 2022-10-14 with reprex v2.0.2

But notice that it is still considered monthly data. You probably want to consider this as annual, so it needs re-indexing.

library(fpp3)
us_employment %>%
  filter(Title == "Retail Trade") %>%
  filter(month(Month) == 7) |> 
  mutate(year = year(Month)) |> 
  as_tsibble(index = year)
#> # A tsibble: 81 x 5 [1Y]
#> # Key:       Series_ID [1]
#>       Month Series_ID     Title        Employed  year
#>       <mth> <chr>         <chr>           <dbl> <dbl>
#>  1 1939 Jul CEU4200000001 Retail Trade    3100   1939
#>  2 1940 Jul CEU4200000001 Retail Trade    3251.  1940
#>  3 1941 Jul CEU4200000001 Retail Trade    3523.  1941
#>  4 1942 Jul CEU4200000001 Retail Trade    3416.  1942
#>  5 1943 Jul CEU4200000001 Retail Trade    3412.  1943
#>  6 1944 Jul CEU4200000001 Retail Trade    3443.  1944
#>  7 1945 Jul CEU4200000001 Retail Trade    3509.  1945
#>  8 1946 Jul CEU4200000001 Retail Trade    4048.  1946
#>  9 1947 Jul CEU4200000001 Retail Trade    4314.  1947
#> 10 1948 Jul CEU4200000001 Retail Trade    4450.  1948
#> # … with 71 more rows

Created on 2022-10-14 with reprex v2.0.2

1 Like

Many thanks for your swift response!

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

If you have a query related to it or one of the replies, start a new topic and refer back with a link.