R - 如何确定周结束日期

时间:2014-11-17 05:31:00

标签: r

假设我有以下数据框

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

这将返回

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

我想看的输出是'星期五'结束日期

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

我已经搜遍了所有,无法找到解决方案。我能找到的最接近的是以下代码

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

但未将输出显示为数据框。

任何帮助将不胜感激!

1 个答案:

答案 0 :(得分:1)

lubridate包中使用ceiling_date。你需要稍微调整一下,因为这会导致下周日而不是周五。

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