如何创建一个新列来指定日期属于哪个年份范围(如学年)?

How to create a new column that specifies which range of years a date belongs to (like academic year)?

在某些情况下,“年”不一定从 1 月 1 日开始循环。例如,美国的学年从八月底开始。再比如NBA赛季。

我的问题:给定包含日期列的数据,我想创建另一个列来表示它属于哪个时期。例如,假设我们得到以下 tib:

library(lubridate, warn.conflicts = FALSE)
library(tibble)

tib <- tibble(my_dates = as_date(c("1999-01-01", "2010-08-09", "2010-09-02", "1995-03-02")))
tib
#> # A tibble: 4 x 1
#>   my_dates  
#>   <date>    
#> 1 1999-01-01
#> 2 2010-08-09
#> 3 2010-09-02
#> 4 1995-03-02

并且我们想要改变一个引用每个日期所属学年的列,前提是该学年从 8 月 31 日开始:

desired_output <- 
  tib %>%
  add_column(belongs_to_school_year = c("1998-1999", "2009-2010", "2010-2011", "1994-1995"))

desired_output
#> # A tibble: 4 x 2
#>   my_dates   belongs_to_school_year
#>   <date>     <chr>                 
#> 1 1999-01-01 1998-1999             
#> 2 2010-08-09 2009-2010             
#> 3 2010-09-02 2010-2011             
#> 4 1995-03-02 1994-1995

如何根据 my_dates 使用 mutate() 创建列 belongs_to_school_year

您可以为此使用 dplyrlubridate

desired_output <- tib %>%
  mutate(school_year = case_when(month(my_dates) <= 8 ~ paste(year(my_dates)-1, year(my_dates), sep = "-"),
                                 month(my_dates) > 8 ~ paste(year(my_dates), year(my_dates)+1, sep = "-")))

或:

desired_output <- tib %>%
  mutate(school_year = if_else(month(my_dates) <= 8, 
                               paste(year(my_dates)-1, year(my_dates), sep = "-"),
                               paste(year(my_dates), year(my_dates)+1, sep = "-")))