R将字符串日期(例如“ 2014年10月1日”)转换为日期格式 [英] R convert string date (e.g. "October 1, 2014") to Date format
本文介绍了R将字符串日期(例如“ 2014年10月1日”)转换为日期格式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如何将日期字符串的向量(如 c( 2014年10月1日, 2014年6月14日)
转换为R <$ c的向量$ c>日期格式?
how can I convert a vector of date string like c("October 1, 2014", "June 14, 2014")
to a vector of R Date
format?
我有一个data.frame,其中一列是上述格式的日期字符串。
I have a data.frame which one column is date string in the above format.
感谢您的帮助。
谢谢!
推荐答案
尝试:
v <- c("October 1, 2014", "June 14, 2014")
as.Date(v, "%B %d,%Y")
哪个给定:
#[1] "2014-10-01" "2014-06-14"
或
strptime(v, "%B %d,%Y")
其中给出:
#[1] "2014-10-01 EDT" "2014-06-14 EDT"
基准
largev <- rep(v, 10e5)
library(microbenchmark)
microbenchmark(
as.Date = as.Date(largev, "%B %d,%Y"),
strptime = strptime(largev, "%B %d,%Y"),
times = 10
)
其中给出:
#Unit: seconds
# expr min lq mean median uq max neval cld
# as.Date 1.479891 1.480671 1.527838 1.483158 1.489222 1.863777 10 a
# strptime 2.177625 2.183247 2.237732 2.255282 2.268452 2.272537 10 b
根据@cory在评论中提到的,请使用?strptime
获取格式代码:
- %B 中的完整月份名称当前语言环境。 (还与输入的缩写名称匹配。)
- %d 每月的天,以十进制数字(01-31)表示。
- %Y 与世纪的年份。请注意,原始格里高利历中没有零,但ISO 8601:2004将其定义为有效(解释为1BC)
- %B Full month name in the current locale. (Also matches abbreviated name on input.)
- %d Day of the month as decimal number (01–31).
- %Y Year with century. Note that whereas there was no zero in the original Gregorian calendar, ISO 8601:2004 defines it to be valid (interpreted as 1BC)
这篇关于R将字符串日期(例如“ 2014年10月1日”)转换为日期格式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文