0

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.

2 Answers2

0

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)
jay.sf
  • 60,139
  • 8
  • 53
  • 110
0

Using lubridate

library(lubridate)
ymd(df$yr_mo, truncated = 1)
#[1] "2012-08-01" "2012-08-01" "2012-08-01"

Or to convert to POSIXct

ymd_hms(df$yr_mo, truncated = 4)
#[1] "2012-08-01 UTC" "2012-08-01 UTC" "2012-08-01 UTC"

data

df <- structure(list(yr_mo = c("2012-08", "2012-08", "2012-08")), 
  class = "data.frame", row.names = c(NA, -3L))
akrun
  • 874,273
  • 37
  • 540
  • 662