How to convert a string factor into Date?

前端 未结 5 1016
情话喂你
情话喂你 2021-01-24 17:52

I\'m working with the London crime dataset which contains dates in an integer format. I melted them and now they have become factors.

For example, \"

相关标签:
5条回答
  • 2021-01-24 17:59

    One possibility is to use lubridate

    ss <- factor("X200801")
    
    library(lubridate)
    ymd(paste(sub("X", "", ss), "01", sep = ""))
    #[1] "2008-01-01"
    
    0 讨论(0)
  • 2021-01-24 18:05

    It can be compactly changed with as.yearmon

    library(zoo)
    as.Date(as.yearmon("X200801", "X%Y%m"))
    #[1] "2008-01-01"
    
    0 讨论(0)
  • 2021-01-24 18:05

    You can use parse_datetime from the readr package:
    testdate <- factor("X200801")
    parse_datetime(as.character(testdate), format = 'X%Y%M')

    I wouldn't recommend using MM/DD/YYY in R. Keeping things in the ISO 8601 format is preferable.

    0 讨论(0)
  • 2021-01-24 18:07

    Using base R we can add the date component using paste0 convert to date object using appropriate format.

    as.Date(paste0("X200801", "01"), format = "X%Y%m%d")
    #[1] "2008-01-01"
    
    0 讨论(0)
  • 2021-01-24 18:13

    Using anytime:

    test=as.factor("X200801")
    library(anytime)
    anydate((gsub("X","",test)))
    [1] "2008-01-01"
    

    As suggested by @akrun we can simply supply a format that will be used within our environment with addFormats and use anydate to convert to date:

    addFormats("X%Y%m")
    anydate("X200801")
    
    0 讨论(0)
提交回复
热议问题