Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
660 views
in Technique[技术] by (71.8m points)

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

I have an R data frame like as shown below

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

I would like to get the no of days to prev year and next year.

I was trying something like the below

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

In python, I know we have something called day of the year and offsets.YearEnd(0) etc which I knew based on this post. But can help me with how to do this using R?

I expect my output to be like as shown below

enter image description here

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You can use ceiling_date and floor_date from lubridate to get first and last days of the year and then subtract it with date_1 to get days_to_previous_year and days_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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...