Search code examples
rposixct

How to turn a column in a data frame to as POSIXct class? Only have month and year


I am trying to convert a set of values to POSIXct class, but it keeps returning NA's. I only have the month and year, and the column is in "YYYY-MM" format. Here is an snippet of the data I have:

yr_mo
"2012-08"
"2012-08"
"2012-08"

Here is the code I have that is returning NA's:

yr_mo <- as.POSIXct(strptime(x=yr_mo, format = "%Y-%m", tz= "America/Los_Angeles"))

I have tried different formats like "%Y-%m-%d" and no luck. I have also tried as.Date and that also did not work.

I am trying to get this data ready for ArcGIS.


Solution

  • You may paste a phantom day.

    as.POSIXct(paste0(d$yr_mo, "-01"), tz="GMT")
    # [1] "2012-08-01 GMT" "2012-08-01 GMT" "2012-08-01 GMT"
    

    Data:

    d <- read.table(text='yr_mo
                    "2012-08"
                    "2012-08"
                    "2012-08"', header=TRUE)