R 将字符串日期(例如 "October 1, 2014")转换为日期格式
R convert string date (e.g. "October 1, 2014") to Date format
如何将 c("October 1, 2014", "June 14, 2014")
之类的日期字符串向量转换为 R Date
格式的向量?
我有一个 data.frame 其中一列是上述格式的日期字符串。
非常感谢你的帮助。
谢谢!
尝试:
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 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)
如何将 c("October 1, 2014", "June 14, 2014")
之类的日期字符串向量转换为 R Date
格式的向量?
我有一个 data.frame 其中一列是上述格式的日期字符串。
非常感谢你的帮助。
谢谢!
尝试:
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 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)