2014-11-17 42 views
0

可以說我有以下數據幀的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"] 

但是不會將輸出顯示爲數據幀。

任何幫助,將不勝感激!

回答

0

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 
+0

謝謝里奇!這很完美!我不知道在lubridate軟件包中有ceiling_date乾杯! – WinteR

相關問題