-1

Can I customize the display format of the time series column in tsibble ?

yearmonth allways like %Y %m,but i would like change the default format to %m-%y all over one chunk

tsibble::format not working

Zeno Shuai
  • 109
  • 3
  • 1
    It's easier to help you if you include a simple [reproducible example](https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example) with sample input and desired output that can be used to test and verify possible solutions. – MrFlick Apr 18 '23 at 14:23

1 Answers1

1

Maybe you're looking for format('%b-%Y')?

df <- data.frame(
  date = c("2022-01-01","2022-02-01","2022-03-01",
           "2022-04-01","2022-05-01","2022-06-01","2022-07-01",
           "2022-08-01","2022-09-01","2022-10-01","2022-11-01","2022-12-01")
)

df |>
  dplyr::mutate(
    date = tsibble::yearmonth(date) |>
      format('%b-%Y')
  )
#>        date
#> 1  Jan-2022
#> 2  Feb-2022
#> 3  Mar-2022
#> 4  Apr-2022
#> 5  May-2022
#> 6  Jun-2022
#> 7  Jul-2022
#> 8  Aug-2022
#> 9  Sep-2022
#> 10 Oct-2022
#> 11 Nov-2022
#> 12 Dec-2022

Another option is to use zoo::yearmon().

df |>
  dplyr::mutate(
    date = zoo::as.yearmon(date)
  )
#>        date
#> 1  Jan 2022
#> 2  Feb 2022
#> 3  Mar 2022
#> 4  Apr 2022
#> 5  May 2022
#> 6  Jun 2022
#> 7  Jul 2022
#> 8  Aug 2022
#> 9  Sep 2022
#> 10 Oct 2022
#> 11 Nov 2022
#> 12 Dec 2022
joshbrows
  • 77
  • 7
  • Thanks! Can I give a option(...) at the beginning or other ways, then use " ts <- dplyr::mutate(df,date =tsibble::yearmonth(date)); print(ts)" all over the code? – Zeno Shuai Apr 21 '23 at 13:53
  • @ZenoShuai Another option is to use `zoo::yearmon()`. That automatically prints the way you want it (assuming the hyphen isn't needed). I updated my answer to show that option. – joshbrows Apr 21 '23 at 18:35