0

I would like do perform the reverse of R converting a factor YYYY-MM to a date.

I have a data frame (df) with dates presented as YYYY-MM-DD format (column "Date1") and would like to convert them into YYYY-MM format. The days range between 0-31 but these aren't necessary for my YYYY-MM format.

The point is that I have another set of columns that are in YYYY-MM format (column "Date2") and want to calculate the differences between them in whole months (values x, y and z in column "Difference(months)")

Date1       Date2    Difference(months)
2008-08-11  1995-02    x
2010-06-18  1972-09    y
2011-04-22  1956-11    z

Doing df$Date1_new <- as.Date(df$Date1, "%Y-%m") just gives a series of "NA" values.

Please can you give me a way that does what I am asking for or another easier method that gives the same desired result?

Community
  • 1
  • 1
Bob
  • 295
  • 2
  • 4
  • 14
  • 2
    You have to first convert them to proper `Date`s and then use `format` – talat Feb 07 '17 at 13:53
  • Please explain what you mean by converting to proper dates and using format. Convert what? – Bob Feb 07 '17 at 13:56
  • 1
    I mean something like `format(as.Date(df$Date1, "%Y-%m-%d"), "%Y-%m")` – talat Feb 07 '17 at 14:01
  • Please can you mark this as an answer. Thank you for your help – Bob Feb 07 '17 at 14:15
  • Another option is using the `as.yearmon` function from the `zoo` library. – Jaap Feb 07 '17 at 14:21
  • @Bob, feel free to put my comment in an answer of your own and mark it as accepted. I believe it's a duplicate question but can't find a good dupe at the moment – talat Feb 07 '17 at 14:25

1 Answers1

7

Using format(as.Date(df$Date1, "%Y-%m-%d"), "%Y-%m") works for converting 2008-08-11 to 2008-08 - as suggested by @docendo discimus

Bob
  • 295
  • 2
  • 4
  • 14