R从多种格式转换为日期 [英] R Convert to date from multiple formats
问题描述
我需要将多种格式的日期字符串转换为有效日期.
I need to convert a string of dates that is in multiple formats to valid dates.
例如
dates <- c("01-01-2017","02-01-2017","12-01-2016","20160901","20161001", "20161101")
> as.Date(dates, format=c("%m-%d-%Y","%Y%m%d"))
[1] "2017-01-01" NA "2016-12-01" "2016-09-01" NA "2016-11-01"
两个日期显示为NA
推荐答案
这差不多是我写的随时软件包:
This is pretty much I wrote the anytime package for:
R> dates <- c("01-01-2017","02-01-2017","12-01-2016","20160901","20161001",
+ "20161101")
R> library(anytime)
R> anydate(dates)
[1] "2017-01-01" "2017-02-01" "2016-12-01" "2016-09-01"
[5] "2016-10-01" "2016-11-01"
R>
可靠地解析任何合理输入,并且没有显式格式或起源或其他线路噪声.
Parse any sane input reliably and without explicit format or origin or other line noise.
话虽这么说,不是从年份开始的ISO风格是在问潜在的麻烦,所以02-03-2017
可能是2月3日或3月2日.我遵循北美公约,我也考虑过坏了-但是太普遍了.请帮自己一个忙,并尝试将输入限制为ISO日期,至少是ISO订单YYYYMMDD.
That being said, not starting ISO style with the year is asking for potential trouble, so 02-03-2017
could be February 3 or March 2. I am following the North American convention I too consider somewhat broken -- but is so darn prevalent. Do yourself a favour and try to limit inputs to ISO dates, at least ISO order YYYYMMDD.
这篇关于R从多种格式转换为日期的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!