Search code examples
rposixstrptime

Strptime fails when working with a dataframe


Strptime seems to be missing something in this scenario:

aDateInPOSIXct <- strptime("2018-12-31", format = "%Y-%m-%d")
someText <- "asdf"
df <- data.frame(aDateInPOSIXct, someText, stringsAsFactors = FALSE)
bDateInPOSIXct <- strptime("2019-01-01", format = "%Y-%m-%d")

df[1,1] <- bDateInPOSIXct

Assignment of bDate to the dataframe fails with:

Error in as.POSIXct.numeric(value) : 'origin' must be supplied

And a warning:

provided 11 variables to replace 1 variables

I want to use both POSIXct dates and POSIXct date-times to compare this and that. It's way less work than manipulating character strings -- and POSIX takes care of the time zone issues. Unfortunately, I'm missing something.


Solution

  • You only need to cast your calls to strptime to POSIXct explicitly:

    aDateInPOSIXct <- as.POSIXct(strptime("2018-12-31", format = "%Y-%m-%d"))
    someText <- "asdf"
    df <- data.frame(aDateInPOSIXct, someText, stringsAsFactors = FALSE)
    bDateInPOSIXct <- as.POSIXct(strptime("2019-01-01", format = "%Y-%m-%d"))
    
    df[1,1] <- bDateInPOSIXct
    

    Check the R documentation which says:

    Character input is first converted to class "POSIXlt" by strptime: numeric input is first converted to "POSIXct".