How to convert a String to Date in R

一曲冷凌霜 提交于 2021-02-05 12:27:28

问题


Is there any way to convert below string to a standard R date class object?

Date_String = "19th January 2020"

Any pointer appreciated.


回答1:


Lubridate can handle it:

> Date_String <- "19th January 2020"
> lubridate::dmy(Date_String)
[1] "2020-01-19"



回答2:


In base R:

# Make sure your locale is English
Sys.getlocale() # can update with Sys.setlocale(LC_TIME = 'en_US.UTF-8')

# Remove "th", more generally the first sequence of lower-case letters
Date_String <- sub("[a-z]+", "", Date_String)
# Now specify the format for as.Date()
as.Date(Date_String, format = "%d %B %Y")
[1] "2020-01-19"



回答3:


    Date_String <- "19th January 2020"

    # Using BASE R
    Date_String <- sub("st|nd|rd|th", "", Date_String)
    as.Date(Date_String, format = "%d %B %Y")
    #> [1] "2020-01-19"

    # Using Lubridate package
    lubridate::dmy(Date_String)
    #> [1] "2020-01-19"


来源:https://stackoverflow.com/questions/61121486/how-to-convert-a-string-to-date-in-r

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!