Bob
Bob

Reputation: 305

Convert date in YYYY-MM-DD format to YYYY-MM

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?

Upvotes: 0

Views: 14811

Answers (1)

Bob
Bob

Reputation: 305

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

Upvotes: 8

Related Questions