rdateposixlubridateposixct

Create start and end date of a calendar year


I would like to create the start and end date of a calendar year from a calendar year variable (here 1991 to 2001), and found a solution:

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 )
  )

Result:

# 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   

it works; but I am looking for a more elegant solution. Thank you for any hint!


Solution

  • Another way, using make_date:

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

    Or

    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))
    

    Output:

    # 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