我有一些字符向量,其中包含各种格式的日期,如下所示
dates <- c("23/11/12", "20/10/2012", "22/10/2012" ,"23/11/12")
我想将它们转换为日期。我已经尝试了 lubridate 包中非常好的 dmy,但这不起作用:
dmy(dates)
[1] "0012-11-23 UTC" "2012-10-20 UTC" "2012-10-22 UTC" "0012-11-23 UTC"
它将 /12 年视为 0012。
所以我现在尝试正则表达式来选择每种类型并使用 as.Date() 单独转换为日期。但是,我尝试仅选择 dd/mm/yy 的正则表达式不起作用。
dates[grep('[0-9]{2}/[0-9]{2}/[0-9]{2,2}', dates)]
returns
[1] "23/11/12" "20/10/2012" "22/10/2012" "23/11/12"
我认为 {2,2} 应该得到正好 2 个数字,而不是全部。我不太擅长正则表达式,因此我们将不胜感激。
Thanks
EDIT
我实际上拥有的是三种不同类型的日期,如下所示
dates <- c("23-Jul-2013", "23/11/12", "20/10/2012", "22/10/2012" ,"23/11/12")
我想将这些转换为日期
parse_date_time(dates,c('dmy'))
gives me
[1] "2013-07-23" "0012-11-23" "2012-10-20" "2012-10-22" "0012-11-23"
然而,这是错误的,0012 应该是 2012。我想要一个(相当简单的)解决方案。
我现在拥有的一种解决方案(感谢@plannapus)是使用正则表达式
实际上我最终创建了这个函数,因为我仍然遇到一些 lubridate 方法将 12 变成 0012 的情况
asDateRegex <- function(dates,
#selects strings from the vector dates using regexes and converts these to Dates
regexes = c('[0-9]{2}/[0-9]{2}/[0-9]{4}', #dd/mm/yyyy
'[0-9]{2}/[0-9]{2}/[0-9]{2}$', #dd/mm/yy
'[0-9]{2}-[[:alpha:]]{3}-[0-9]{4}'), #dd-mon-yyyy
orders = 'dmy',
...){
require(lubridate)
new_dates <- as.Date(rep(NA, length(dates)))
for(reg in regexes){
new_dates[grep(reg, dates)] <- as.Date(parse_date_time(dates[grep(reg, dates)], order = orders))
}
new_dates
}
asDateRegex (dates)
[1] "2012-10-20" "2013-07-23" "2012-11-23" "2012-10-22" "2012-11-23"
但这不是很优雅。还有更好的解决方案吗?