[英]Adding the Century to 2-Digit Year
我目前有一個看起來像的 df
STA YR MO DA MAX date
58716 33013 43 3 11 60 0043-03-11
58717 33013 43 3 12 55 0043-03-12
58718 33013 43 3 13 63 0043-03-13
58719 33013 43 3 14 50 0043-03-14
58720 33013 43 3 15 58 0043-03-15
58721 33013 43 3 16 63 0043-03-16
如您所見,我做了df$date <- as.Date(with(df, paste(YR, MO, DA,sep="-")), "%Y-%m-%d")
來獲取日期列,但顯然因為年份列前面沒有“19”,日期中的年份顯得古怪。 這些都是 19xx 日期。 什么是解決這個問題的好方法?
嘗試
df$date <- as.Date(with(df, paste(1900+YR, MO, DA,sep="-")), "%Y-%m-%d")
你應該使用%y
因為你有兩位數的年份。
df$date <- as.Date(with(df, paste(YR, MO, DA,sep="-")), "%y-%m-%d")
但是,這並不能解決您的問題,因為小於 69 的任何東西都會在 2 位數年份中以 20 為前綴,因此 43 變為 2043。
如果你知道你所有的年份都是19XX
的形式,你可以這樣做
df$date <- as.Date(with(df, sprintf('19%d-%d-%d', YR, MO, DA)))
如果您的年份包含超過一個世紀的 2 位數年份,則此代碼會將它們全部轉換為過去的有效日期(沒有未來日期)。
dates_y2Y <- function(y,m,d) {
library(stringr)
y <- stringr::str_pad(y, width=2, pad="0")
m <- stringr::str_pad(m, width=2, pad="0")
d <- stringr::str_pad(d, width=2, pad="0")
toyear <- format(Sys.Date(), "%y")
tomnth <- format(Sys.Date(), "%m")
today <- format(Sys.Date(), "%d")
as.Date(
ifelse(y<toyear | y==toyear & m<tomnth | y==toyear & m==tomnth & d<=today,
as.Date(paste(y,m,d,sep="-"), format="%y-%m-%d"),
as.Date(paste(paste0("19",y),m,d,sep="-"), format="%Y-%m-%d"))
, origin="1970-01-01")
}
df$date <- dates_y2Y(df$YR, df$MO, df$DA)
df
STA YR MO DA date
1 33013 23 1 31 1923-01-31
2 33013 43 2 30 <NA>
3 33013 63 5 5 1963-05-05
4 33013 83 7 27 1983-07-27
5 33013 3 12 9 2003-12-09
6 33013 20 4 21 2020-04-21
7 33013 20 4 22 1920-04-22
數據:
df <- structure(list(STA = c(33013L, 33013L, 33013L, 33013L, 33013L,
33013L, 33013L), YR = c(23L, 43L, 63L, 83L, 3L, 20L, 20L), MO = c(1L,
2L, 5L, 7L, 12L, 4L, 4L), DA = c(31L, 30L, 5L, 27L, 9L, 21L,
22L), date = structure(c(-17137, NA, -2433, 4955, 12395, 18373,
-18151), class = "Date")), row.names = c(NA, -7L), class = "data.frame")
另一種解決方案
library(lubridate)
df %>%
mutate(date = make_date(year = 1900 + YR, month = MO, day = DA))
sprintf
的另一個選擇
df$date <- as.Date(do.call(sprintf, c(f = '19%d-%d-%d', df[2:4])))
或與unite
library(dplyr)
library(tidyr)
library(stringr)
df %>%
mutate(YR = str_c('19', YR)) %>%
unite(date, YR, MO, DA, sep="-", remove = FALSE) %>%
mutate(date = as.Date(date))
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.