问题
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