[英]Why is the chron package treating 2 digit years oddly starting from 2030?
我最近注意到 RI 中的一個奇怪行為無法解釋。 我在一些舊代碼中有這個:
以下應生成從 01/1980 -> 01/2029 的月份列表,並且按預期工作:
length(chron::seq.dates("01/31/80", "01/03/29", by="months"))
[1] 588
這就是事情變得奇怪的地方。 以下與上述相同,但應生成到 2030 年的日期:
length(chron::seq.dates("01/31/80", "01/03/30", by="months"))
Error during wrapup: "from" must be a date before "to"
那么這里發生了什么?
將兩位數的年份擴展為 4 位數的年份時,默認情況下 chron 截止值為 30。 也就是說,如果兩位數年份小於 30,則假定為 20yy,否則為 19yy。 這由chron.year.expand
選項控制,該選項默認設置為 chron year.expand
函數,該函數的默認截止值為 30,但可以按如下方式更改:
library(chron)
# change cutoff to 50
options(chron.year.expand =
function (y, cut.off = 50, century = c(1900, 2000), ...) {
chron:::year.expand(y, cut.off = cut.off, century = century, ...)
}
)
length(seq.dates("01/31/80", "01/03/30", by="months"))
## [1] 600
這些中的每一個也可以工作並且不需要設置chron.year.expand
:
length(seq(as.chron("1980-01-31"), as.chron("2030-01-03"), by="months"))
length(seq.dates("01/31/80", as.chron("2030-01-03"), by="months"))
length(seq.dates("01/31/80", chron(julian(1, 3, 2030)), by="months"))
length(seq.dates("01/31/80", julian(1, 3, 2030), by="months"))
length(as.chron(seq(as.Date("1980-01-31"), as.Date("2030-01-03"), by = "month")))
length(seq.dates("01/31/80", length = 600, by="months"))
最好轉換為Date
類,因為當我們延長年份時,2 位數年份可能是一個問題。
library(chron)
date1 <- as.Date("01/31/80", format = "%m/%d/%y")
date2 <- as.Date("01/03/30", format = "%m/%d/%y")
在這里,轉換是正確的
date1
#[1] "1980-01-31"
date2
#[1] "2030-01-03"
基於對?seq.dates
,或者我們可以通過一個character
的字符串或numeric
值(“日期”類轉換為“數字”
length(seq.dates(as.numeric(date1), as.numeric(date2), by = "months"))
#[1] 600
或julian
約會
j1 <- julian(date1, origin = as.Date('1970-01-01'))
j2 <- julian(date2, origin = as.Date('1970-01-01'))
length(seq.dates(j1, j2, by = 'months'))
#[1] 600
或使用character
格式的 4 位年份
length(chron::seq.dates("01/31/1980", "01/03/2030", by="months"))
#[1] 600
如果日期已經有 2 位數字,可以使用sub
插入特定數字
sub("(\\d+)$", "20\\1", "01/03/30")
#[1] "01/03/2030"
並在seq.dates
傳遞該值
length(seq.dates("01/31/80", sub("(\\d+)$", "20\\1", "01/03/30"), by = "months"))
#[1] 600
使用在 Linux Mint 上運行的 R4.1,下面的代碼顯示了我所看到的。 默認截止值似乎是 68,而不是 30。有沒有辦法在給定的 R 安裝中將真正的默認截止值指定為 30? 換句話說,我不想每次運行 R 時都必須運行上面給出的選項函數將其設置為 30。
圖書館(時間)
chron("2/29/68")-chron("11/23/69") 時間天數:[1] 35892
chron("2/29/1968")-chron("11/23/1969") [1] -633
選項(chron.year.expand =
function (y, cut.off = 30, century = c(1900, 2000), ...) {
chron:::year.expand(y, cut.off = cut.off, century = century, ...)
}
chron("2/29/68")-chron("11/23/69") [1] -633
chron("2/29/1968")-chron("11/23/1969") [1] -633
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.