R convert string date (e.g. “October 1, 2014”) to Date format

让人想犯罪 __ 提交于 2019-12-17 21:16:43

问题


how can I convert a vector of date string like c("October 1, 2014", "June 14, 2014") to a vector of R Date format?

I have a data.frame which one column is date string in the above format.

I would appreciate your help.

Thanks!


回答1:


Try:

v <- c("October 1, 2014", "June 14, 2014") 
as.Date(v, "%B %d,%Y")

Which gives:

#[1] "2014-10-01" "2014-06-14"

Or

strptime(v, "%B %d,%Y")

Which gives:

#[1] "2014-10-01 EDT" "2014-06-14 EDT"

Benchmark

largev <- rep(v, 10e5)

library(microbenchmark)
microbenchmark(
  as.Date = as.Date(largev, "%B %d,%Y"),
  strptime = strptime(largev, "%B %d,%Y"),
  times = 10
)

Which gives:

#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

As per mentionned by @cory in the comments, use ?strptime to get the format codes:

  • %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)


来源:https://stackoverflow.com/questions/37141431/r-convert-string-date-e-g-october-1-2014-to-date-format

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!