1

I have dates formatted as 'year_month' like so:

# A tibble: 6 x 4
  IND_LOC year_month total_this_month data             
  <fct>   <fct>                 <dbl> <list>           
1 8_9     2013_01            3960268. <tibble [11 × 8]>
2 8_9     2013_02            3051909. <tibble [11 × 8]>
3 8_9     2013_03            3504636. <tibble [11 × 8]>
4 8_9     2013_04            3234451. <tibble [11 × 8]>
5 8_9     2013_05            3409146. <tibble [12 × 8]>
6 8_9     2013_06            3619219. <tibble [12 × 8]>

I would like the 'year_month' column to be of class 'date' showing 'Jan-2013' etc. instead of 2013_01.

I'm also trying to convert this dataframe into a timeseries, though I imagine this will be considerably easier once I have a proper date column...

I've tried several lubridate options though I think the current format of my "dates" are so unconventional that it just doesn't know what to do with them?

Any help with this is greatly appreciated!

Davide Lorino
  • 875
  • 1
  • 9
  • 27
  • 2
    It is currently showing `2013_01`, but `Jan-2013` is also not a Date class If you need a date class `as.Date(zoo::as.yearmon(df$year_month, "%Y_%m"))` |to get the format you required `format(as.Date(as.yearmon("2013_01", "%Y_%m")), "%b-%Y")# [1] "Jan-2013"` – akrun May 19 '18 at 04:45
  • 3
    A month and a year is not a complete date. You need to add a day to it or use the `yearmon` class from the `zoo` package. E.g. - see https://stackoverflow.com/questions/6242955/converting-year-and-month-yyyy-mm-format-to-a-date – thelatemail May 19 '18 at 04:46
  • 1
    Thanks a lot guys, really appreciate your help! – Davide Lorino May 19 '18 at 04:51
  • 1
    One of the way is to have 2 features (year, month) by using "year<-unlist(strsplit("2013_01", "_"))[1]" for "year" for example. Working with 2 features can be more correct than adding "day" as this feature do not exist in the actual data set – Andrii May 19 '18 at 05:02
  • @Akrun your method for getting the format i'm looking for is perfect, however i'm having trouble as I believe the as.yearmon("2013_01", "%Y_%m") part is converting all of my dates to "2013_01", is it possible to convert all dates to their corresponding date rather than just 2013_01? – Davide Lorino May 19 '18 at 05:15
  • 2
    Sorry, I was just showing a simple example, what i meant is `as.yearmon(df$year_month, "%Y_%m")` where `df` is your dataframe object\ – akrun May 19 '18 at 05:16

0 Answers0