2015-09-07 19 views
1

我需要找到所有對應於一組日期的'下一個星期五'。如何找到下一個特定的日子?

例如2015-08-03(2015年8月3日星期一)作爲輸入,應返回2015-08-07(2015年8月7日星期五)作爲輸出。

我找不到一種方法來管理這種需求,而閱讀lubridate's vignette,你會如何繼續?

library(lubridate) 
date <- "2015-08-03" 
date <- wmd(date) 
wday(date, label = TRUE) 
+2

你讀過http://stackoverflow.com/questions/28971638/r-obtaining-last-fridays-date? – lukeA

回答

3

試試這個功能:

nextweekday <- function(date, wday) { 
    date <- as.Date(date) 
    diff <- wday - wday(date) 
    if(diff < 0) 
    diff <- diff + 7 
    return(date + diff) 
} 

您插入日期和所需wday(星期日= 1,星期一= 2,...),並得到你想要的結果。

1

Lubridate提供了一個很好的功能持續時間。您可以使用此功能將日期添加到當前日期。

通常最好不要創建一個與函數名稱相同的變量(即日期)。

the_date <- "2015-08-03" 
the_date <- ymd(the_date) 
wday(the_date, label = TRUE) 

next_friday <- function(given_date){ 
    n_days_to_fri <- 6 - wday(given_date) 
    z <- given_date + duration(n_days_to_fri, "days") 
    return(z) 
} 

next_friday(the_date) 
[1] "2015-08-07 UTC" 
wday(next_friday(the_date), label = TRUE) 
[1] Fri 
Levels: Sun < Mon < Tues < Wed < Thurs < Fri < Sat 
2
library(lubridate) 

nextFriday <- function(date) { 
    date <- ymd(date) 
    .day <- wday(date, label = TRUE) 
    shift <- ifelse(as.numeric(.day) < 6, 0, 7) 
    date + days(6 - as.numeric(.day) + shift) 
} 

nextFriday("2015-08-03") 
相關問題