使用 R 获得前一年和明年的天数的优雅方法?

Elegant way to get no of days to prev and next year using R?

我有一个如下所示的 R 数据框

test_df <- data.frame("subbject_id" = c(1,2,3,4,5), 
          "date_1" = c("01/01/2003","12/31/2007","12/30/2008","01/02/2007","01/01/2007"))

我想得到上一年和明年的天数。

我正在尝试类似下面的方法

library(lubridate)
test_df$current_yr = year(mdy(test_df$date_1))
prev_yr = test_df$current_yr - 1 #(subtract 1 to get the prev year)
next_yr = test_df$current_yr + 1 #(add 1 to get the prev year)
days_to_prev_yr = days_in_year(current_yr) # this doesn't work

在python中,我知道我们有一些叫做day of the yearoffsets.YearEnd(0)等的东西,我是根据这个知道的。但是可以帮助我如何使用 R 来做到这一点吗?

我希望我的输出如下所示

您可以使用 ceiling_datefloor_datelubridate 得到一年的第一天和最后一天,然后用 date_1 减去它得到 days_to_previous_yeardays_to_next_year.

library(dplyr)
library(lubridate)

test_df %>%
  mutate(date_1 = mdy(date_1), 
         previous_year = floor_date(date_1, 'year'), 
         next_year = ceiling_date(date_1, 'year') - 1, 
         days_to_previous_year = as.integer(date_1 - previous_year), 
         days_to_next_year = as.integer(next_year - date_1)) %>%
  select(-previous_year, -next_year)


#  subbject_id     date_1 days_to_previous_year days_to_next_year
#1           1 2003-01-01                     0               364
#2           2 2007-12-31                   364                 0
#3           3 2008-12-30                   364                 1
#4           4 2007-01-02                     1               363
#5           5 2007-01-01                     0               364

一个dplyrlubridate选项可以是:

test_df %>%
 mutate(date_1 = mdy(date_1),
        days_to_prev_year = date_1 - mdy(paste0("01-01-", year(date_1))),
        days_to_next_year = mdy(paste0("12-31-", year(date_1))) - date_1)

  subbject_id     date_1 days_to_prev_year days_to_next_year
1           1 2003-01-01            0 days          364 days
2           2 2007-12-31          364 days            0 days
3           3 2008-12-30          364 days            1 days
4           4 2007-01-02            1 days          363 days
5           5 2007-01-01            0 days          364 days