Split up date yyyymm into two columns

I have a data.table, where I want to split the date column which is in "YYYYMM" into two columns = "YYYY" "MM".
I tried this , but it returns NA on the entire 'mdate' column, and therefore doesn't work for the last two lines either.

Hi Andreas,

I'm not sure what your end goal is of splitting this into two columns, but assuming that your mdate column is already of class Date, it should suffice to only use the last two lines of your code.

The format() function is intended for pretty printing and, for this specific purpose, requires a date object.

If this is not helping you further, can you please provide a reprex (reproducible example) so that we can assist you better?

You can't have a date that is a month and year. A date is a day of that month. So there are a few ways to tackle this depending what your end goal is and the quality of your data.

If you consider February 2021 to be 2021-02-01 and you currently have myDate = "202102"

Add the 01 on the end and then do the date manipulation:

myDate <- "202102"
myDate <- paste0( myDate, "01")
myRealDate <- as.Date ( myDate )
myYear <- format(myRealDate, "%Y")
myMonth <- format (myRealDate, "%m")

Or you could use string manipulation to get the first four and last 2 characters

myDate <- "202102"
myYear <- substr( myDate, 1, 4)
myMonth <- substr( myDate, 5, 6)

What you plan to do with them will depend what the right solution is.

Output will be character, but can be made numeric.

First example can be made slicker by nesting

Thank you! The last suggestion works perfect!

This topic was automatically closed 21 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.