[英]Format for ordinal dates (day of month with suffixes -st, -nd, -rd, -th)
我錯過了什么嗎? 我無法弄清楚如何將以下轉換Date
s,其中當月(當天%d
)具有序后綴-st
, -nd
, -rd
, -th
:
ord_dates <- c("September 1st, 2016", "September 2nd, 2016",
"September 3rd, 2016", "September 4th, 2016")
?strptime
似乎沒有列出序數后綴的簡寫,也不會自動處理:
as.Date(ord_dates, format = c("%B %d, %Y"))
#[1] NA NA NA NA
是否有用於處理format
參數中被忽略字符的標記? 我丟失的令牌?
我能想到的最好的是(可能有一個更短的正則表達式,但同樣的想法):
as.Date(gsub("([0-9]+)(st|nd|rd|th)", "\\1", ord_dates), format = "%B %d, %Y")
# [1] "2016-09-01" "2016-09-02" "2016-09-03" "2016-09-04"
看起來這種數據應該比較普遍; 我錯過了什么嗎?
享受lubridate
的力量:
library(lubridate)
mdy(ord_dates)
[1] "2016-09-01" "2016-09-02" "2016-09-03" "2016-09-04"
在內部, lubridate
沒有任何特殊的轉換規范來實現這一點。 相反, lubridate
首先使用(通過智能猜測)格式"%B %dst, %Y"
。 這將獲取ord_dates
的第一個元素。
然后檢查NA
並對剩余元素重復其智能猜測,確定"%B %dnd, %Y"
以獲取第二個元素。 它以這種方式繼續直到沒有NA
剩余(在這種情況下發生在 4 次迭代之后),或者直到它的智能猜測未能找到可能的格式候選。
您可以想象這會使lubridate
變慢,而且確實如此 - 僅使用上面@alistaire 建議的智能正則表達式的速度大約是其一半:
set.seed(109123)
ord_dates <- sample(
c("September 1st, 2016", "September 2nd, 2016",
"September 3rd, 2016", "September 4th, 2016"),
1e6, TRUE
)
library(microbenchmark)
microbenchmark(times = 10L,
lubridate = mdy(ord_dates),
base = as.Date(sub("\\D+,", "", ord_dates),
format = "%B %e %Y"))
# Unit: seconds
# expr min lq mean median uq max neval cld
# lubridate 2.167957 2.219463 2.290950 2.252565 2.301725 2.587724 10 b
# base 1.183970 1.224824 1.218642 1.227034 1.228324 1.229095 10 a
lubridate
的明顯優勢是其簡潔性和靈活性。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.