lubridate: how to parse month-year?

28,083
library(zoo)
as.yearmon(mymonth, "%m/%Y")
[1] "Oct 2015" "Nov 2016" "Dec 2016"

as.Date(as.yearmon(mymonth, "%m/%Y"))
[1] "2015-10-01" "2016-11-01" "2016-12-01"

or another workaround,

as.Date(paste0("01/", mymonth),format = "%d/%m/%Y")
[1] "2015-10-01" "2016-11-01" "2016-12-01"
Share:
28,083
ℕʘʘḆḽḘ
Author by

ℕʘʘḆḽḘ

a noobie not so noobie after all.

Updated on July 05, 2022

Comments

  • ℕʘʘḆḽḘ
    ℕʘʘḆḽḘ almost 2 years

    I have a column of dates as follows,

    > mymonth = c('10/2015','11/2016','12/2016')
    > data <- data_frame(mymonth)
    > data
    # A tibble: 3 × 1
      mymonth
        <chr>
    1 10/2015
    2 11/2016
    3 12/2016
    

    Here, obviously, my month corresponds to a particular month in the year. October 2015, November 2015 and December 2015.

    I cannot parse these dates correctly with lubridate. It is assumed the month correspond to the last business day of the month.

    How can I have this variable translated into a date variable that lubridate understands?

    Thanks~

  • ℕʘʘḆḽḘ
    ℕʘʘḆḽḘ over 7 years
    thanks @joel.wilson. the zoo solution, it is compatible with ggplot and lubridate?
  • joel.wilson
    joel.wilson over 7 years
    didn't get the real purpose compatible with lubridate? never tried with ggplot2 package actually
  • David Arenburg
    David Arenburg over 7 years
    Again, Google
  • Nick
    Nick about 4 years
    Adding a bit of currency to this post: You could use lubridate's parse_date_time function as follows format(lubridate::parse_date_time(mymonth, orders = c("m/Y")), "%m-%Y")
  • Jakob
    Jakob about 3 years
    The comment of Nick is the only thing here that actually answers the question for people trying to understand lubriate (who will end up here after googling). @joel.wilson do you want to update your answer?