1

The date columns in my df have only year and month as a string (eg "2009-09"), and therefore conversion to datetime using as.POSIXct doesn't seem to work.

I considered the following solution to fix this:

df$col <- past0(df$col, '-01')
df$col <- as.POSITXct(df$col, format='%Y-%m-%d', tz='UCT')

Which seems to work. My questions are:

  1. Is this indeed an acceptable solution or may I encounter problems further down the line?
  2. Is there a way of dealing with this directly with as.POSITXct that would make redundant the line that pastes the day?

EDIT for any future readers: My question is answered here Converting year and month ("yyyy-mm" format) to a date?

I couldn't find it during my initial searches.

JED HK
  • 216
  • 1
  • 8

1 Answers1

2

It is an underspecified problem. A date needs year, month and day. Now, some helper functions add the date (by convention the first) to help you. anydate() is one:

> vector1 <- c("2009-08", "2009-10", "2010-08")
> vector2 <- c("2009-08", "2009-07", "2009-09")
> anytime::anydate(c(vector1, vector2))
[1] "2009-08-01" "2009-10-01" "2010-08-01" "2009-08-01" "2009-07-01" "2009-09-01"
> 

The returned object is of the desired type:

> class(anytime::anydate(c(vector1, vector2)))
[1] "Date"
> 
Dirk Eddelbuettel
  • 360,940
  • 56
  • 644
  • 725