繁体   English   中英

如何在 R 中将字符串转换为日期

[英]How to convert a String to Date in R

有没有办法将下面的字符串转换为标准的 R 日期 class object?

Date_String = "19th January 2020"

任何指针表示赞赏。

Lubridate可以处理它:

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

在基础 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"
    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"

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM