创建日历年的开始日期和结束日期

Create start and end date of a calendar year

提问人:Julian 提问时间:9/14/2023 最后编辑:MarkJulian 更新时间:9/29/2023 访问量:49

问:

我想从日历年变量(此处为 1991 年到 2001 年)创建日历年的开始和结束日期,并找到了一个解决方案:

library(lubridate)
library(dplyr)
df <- tibble(calendar_year = seq(1991, 2001, 1)) 

df |>
  mutate(
    calendar_year_start_date = ymd("1991-01-01") + 
      years(calendar_year - 1991),
    calendar_year_end_date = ymd("1991-12-31") + 
      years(calendar_year - 1991 )
  )

结果:

# A tibble: 11 × 3
   calendar_year calendar_year_start_date calendar_year_end_date
           <dbl> <date>                   <date>                
 1          1991 1991-01-01               1991-12-31            
 2          1992 1992-01-01               1992-12-31            
 3          1993 1993-01-01               1993-12-31            
 4          1994 1994-01-01               1994-12-31            
 5          1995 1995-01-01               1995-12-31            
 6          1996 1996-01-01               1996-12-31            
 7          1997 1997-01-01               1997-12-31            
 8          1998 1998-01-01               1998-12-31            
 9          1999 1999-01-01               1999-12-31            
10          2000 2000-01-01               2000-12-31            
11          2001 2001-01-01               2001-12-31   

它有效;但我正在寻找一个更优雅的解决方案。谢谢你的任何提示!

R 日期 POSIX 润滑剂 POSIXCT

评论


答:

5赞 Georgery 9/14/2023 #1

好吧,日历年总是在同一天开始和结束,那么这是怎么回事:

tibble(calendar_year = seq(1991, 2001, 1)) |> 
    mutate(calendar_year_start_date = ymd(paste0(calendar_year, "0101")),
           calendar_year_end_date = ymd(paste0(calendar_year, "1231")))
5赞 Mark 9/14/2023 #2

另一种方式,使用make_date

df |> mutate(start_date = make_date(calendar_year, 1, 1),
            end_date = make_date(calendar_year, 12, 31))

df |> mutate(start_date = ymd(calendar_year, truncated = 2), # credit to Uwe: https://stackoverflow.com/a/48489338/4145280
             end_date = ceiling_date(start_date, "year") - days(1))

输出:

# A tibble: 11 × 3
   calendar_year start_date end_date  
           <dbl> <date>     <date>    
 1          1991 1991-01-01 1991-12-31
 2          1992 1992-01-01 1992-12-31
 3          1993 1993-01-01 1993-12-31
 4          1994 1994-01-01 1994-12-31
 5          1995 1995-01-01 1995-12-31
 6          1996 1996-01-01 1996-12-31
 7          1997 1997-01-01 1997-12-31
 8          1998 1998-01-01 1998-12-31
 9          1999 1999-01-01 1999-12-31
10          2000 2000-01-01 2000-12-31
11          2001 2001-01-01 2001-12-31