如何将R中的字符转换为日期?

如何将R中的字符转换为日期?,r,sparkr,R,Sparkr,我有一个excel文件,其中日期的格式如下。 2020年1月1日 2015年6月3日 我需要把它转换成日期。我尝试过许多转换技术。每次我都会得到NA。这应该可以做到: x <- c("01-Jan-2020", "03-Jun-2015") as.Date(x, format = "%d-%b-%Y") #> [1] "2020-01-01" "2015-06-03" # Or with lubridate lubridate::dmy(x) #> [1] "2020-01

我有一个excel文件,其中日期的格式如下。 2020年1月1日 2015年6月3日

我需要把它转换成日期。我尝试过许多转换技术。每次我都会得到NA。

这应该可以做到:

x <- c("01-Jan-2020", "03-Jun-2015")

as.Date(x, format = "%d-%b-%Y")
#> [1] "2020-01-01" "2015-06-03"

# Or with lubridate
lubridate::dmy(x)
#> [1] "2020-01-01" "2015-06-03"
下载并安装“Lubridate”库

它包含一个名为“parse_date_time2()的方法” 您可以以任何格式解析日期。 前

查阅参考资料。

您是否尝试过使用.Date(variable)?另外,请包括您的数据和您尝试过的内容,这样我们就不会浪费您的时间建议您已经尝试过的内容。Date and lubridate::mdy我尝试过使用.Date and lubridate::mdy,但我没有得到结果。您需要将其与您的数据样本以及您获得的输出一起放入您的问题中3$input列表:POSIXct[1:12274],格式:NA…$润滑油:日期[1:12274],格式:NA…$基础:日期[1:12274],格式:NA NA NA…样本数据:-01-FEB-2046 01-MAR-2019 30-APR-2021 09-MAY-2022 09-MAY-2022 01-MAR-2038 01-SEP-2022 01-AUG-2032 01-AUG-2044 25-OCT-2017lubridate::parse_Date_time2(“2017年1月21日”,orders=“dmy”)::output-NAI通过将数据中的“-”替换为“/”解决了这个问题。它对我很有效
y <- list(input = x,
          lubridate = lubridate::dmy(x),
          base = as.Date(x, format = "%d-%b-%Y"))

str(y)

#> List of 3
#> $ input    : chr [1:2] "01-Jan-2020" "03-Jun-2015"
#> $ lubridate: Date[1:2], format: "2020-01-01" "2015-06-03"
#> $ base     : Date[1:2], format: "2020-01-01" "2015-06-03"
wget https://github.com/tidyverse/lubridate/archive/v1.6.0.tar.gz
sudo R CMD INSTALL v1.6.0.tar.gz
parse_date_time2("21 Jan 2010", orders = "dmy")