WinteR
WinteR

Reputation: 55

R - How to determine the week ending date

Lets say i have the following data frame

  df<-structure(data.frame(date=c("2014-11-04",'2014-11-12','2014-11-17'),volume=c("5","10","2")))

this will return

  date      volume
2014-11-04      5
2014-11-12     10
2014-11-17      2

The output i want to see is the 'Friday' week ending date

  Week Ending volume
1 2014-11-07      5
2 2014-11-14     10
3 2014-11-21      2

i have searched all over and couldnt find a solution. the closest i could find was the below code

df$date[weekdays(df$date)=="Friday"] 

but is not displaying the output as a data frame.

Any help would be appreciated!

Upvotes: 3

Views: 6070

Answers (1)

Richie Cotton
Richie Cotton

Reputation: 121177

Use ceiling_date in the lubridate package. You need to fiddle it a bit, since that rounds up to the next Sunday rather than Friday.

x <- seq(Sys.Date(), by = "1 day", length.out = 21)
data.frame(
  x = x,
  weekday = weekdays(x),
  next_friday = ceiling_date(x, "week") + 
    ifelse(weekdays(x) %in% c("Saturday", "Sunday"), 5, -2)
)
##              x   weekday next_friday
##  1  2014-11-17    Monday  2014-11-21
##  2  2014-11-18   Tuesday  2014-11-21
##  3  2014-11-19 Wednesday  2014-11-21
##  4  2014-11-20  Thursday  2014-11-21
##  5  2014-11-21    Friday  2014-11-21
##  6  2014-11-22  Saturday  2014-11-28
##  7  2014-11-23    Sunday  2014-11-28
##  8  2014-11-24    Monday  2014-11-28
##  9  2014-11-25   Tuesday  2014-11-28
##  10 2014-11-26 Wednesday  2014-11-28
##  11 2014-11-27  Thursday  2014-11-28
##  12 2014-11-28    Friday  2014-11-28
##  13 2014-11-29  Saturday  2014-12-05
##  14 2014-11-30    Sunday  2014-12-05
##  15 2014-12-01    Monday  2014-12-05
##  16 2014-12-02   Tuesday  2014-12-05
##  17 2014-12-03 Wednesday  2014-12-05
##  18 2014-12-04  Thursday  2014-12-05
##  19 2014-12-05    Friday  2014-12-05
##  20 2014-12-06  Saturday  2014-12-12
##  21 2014-12-07    Sunday  2014-12-12

Upvotes: 4

Related Questions