使用R获取星期几的开始和结束日期

时间:2020-05-25 04:51:27

标签: r shiny

我想找到输入日期的一周的开始和结束。即星期天和星期六。

app.R

library(shiny)
library(lubridate)

shinyApp(
  ui = fluidPage(
    dateInput("date", "date"),
    textOutput("date_sun"),
    textOutput("date_satur")
  ),
  
  server = function(input, output) {
    observe({
      
      date_sel <- input$date
      week <- wday(date_sel)
      
      if(week == 1){
        sun <- date_sel
        satur <- date_sel + 6
      }else if(week == 2){
        sun <- date_sel - 1
        satur <- date_sel + 5
      }else if(week == 3){
        sun <- date_sel - 2
        satur <- date_sel + 4
      }else if(week == 4){
        sun <- date_sel - 3
        satur <- date_sel + 3
      }else if(week == 5){
        sun <- date_sel - 4
        satur <- date_sel + 2
      }else if(week == 6){
        sun <- date_sel - 5
        satur <- date_sel + 1
      }else if(week == 7){
        sun <- date_sel - 6
        satur <- date_sel
      }
      
      output$date_sun <- renderPrint(sun)
      output$date_satur <- renderPrint(satur)
      
    })
  })

通过以上代码实现。但这并不漂亮。 难道不是更简洁的代码? 谢谢

2 个答案:

答案 0 :(得分:4)

实际上,我们可以使用strftime在基数R中很轻松地处理此问题,以获得工作日编号(0到6):

x <- as.Date("2020-01-01")    # January 1 was a Wednesday
x - as.numeric(strftime(x, "%w"))
x + 7 - as.numeric(strftime(x, "%w")) - 1

[1] "2019-12-29"
[1] "2020-01-04"

请注意,2019年12月29日是星期日,而2020年1月4日是星期六。

答案 1 :(得分:2)

lubridate中,您可以将floor_date与{{1}一起使用ceiling_dateunits作为'weeks',以获取一周的开始和结束日期。

library(lubridate)
x <- as.Date("2020-01-01") 
floor_date(x, 'weeks')
#[1] "2019-12-29"

ceiling_date(x, 'weeks') - 1
#[1] "2020-01-04"