R Shiny DateRange仅输入月份年份

时间:2016-12-07 07:58:14

标签: r shiny date-range shinydashboard

有没有办法在Shiny中创建一个dateRangeInput()选择器,以便它只选择月份(没有一天),或者它是否自动选择所选月份的第一天而不显示日期选择?或者我应该创建另一个月份日期选择器(滑块,选择框......)

dateRangeInput('dateRange',label = "Pédiode d'analyse : ",format = "mm/yyyy",language="fr",
    start = Sys.Date() %m-% months(12), end=Sys.Date(),startview = "year",separator = " - ")

我想要的是在选择日期时删除此步骤:dateRangeInput

2 个答案:

答案 0 :(得分:3)

查看下面的自定义函数monthStart,该函数可用于强制将日期强制转换为该月份和年份的第一个日期

示例1,显示给定月份的第一天。如果您想使用日期对象以便以后在您的应用中使用,这可能很有用,因此它总是指向给定月份和年份的第一天

#rm(list=ls())
library(shiny)

monthStart <- function(x) {
  x <- as.POSIXlt(x)
  x$mday <- 1
  as.Date(x)
}

ui <- basicPage(dateRangeInput('dateRange',label = "Pédiode d'analyse : ",format = "mm/yyyy",language="fr",start = Sys.Date(), end=Sys.Date(),startview = "year",separator = " - "),
                textOutput("SliderText")
)
server <- shinyServer(function(input, output, session){

  Dates <- reactiveValues()
  observe({
    Dates$SelectedDates <- c(as.character(monthStart(input$dateRange[1])),as.character(monthStart(input$dateRange[2])))
  })
  output$SliderText <- renderText({Dates$SelectedDates})
})
shinyApp(ui = ui, server = server)

enter image description here

示例2,仅显示月份和年份

#rm(list=ls())
library(shiny)

monthStart <- function(x) {
  x <- as.POSIXlt(x)
  x$mday <- 1
  as.Date(x)
}

ui <- basicPage(dateRangeInput('dateRange',label = "Pédiode d'analyse : ",format = "mm/yyyy",language="fr",start = Sys.Date(), end=Sys.Date(),startview = "year",separator = " - "),
                textOutput("SliderText")
)
server <- shinyServer(function(input, output, session){

  Dates <- reactiveValues()
  observe({
    Dates$SelectedDates <- c(as.character(format(input$dateRange[1],format = "%m/%Y")),as.character(format(input$dateRange[2],format = "%m/%Y")))
  })
  output$SliderText <- renderText({Dates$SelectedDates})
})
shinyApp(ui = ui, server = server)

enter image description here

答案 1 :(得分:0)

我刚刚使用airDatePicker()来做到这一点。您可以将弹出式日历的最小视图编辑为“月”,并将日期格式选择为“ yyyy-mm”。

airDatepickerInput("input_var_name",
                   label = "Start month",
                   value = "2015-10-01",
                   maxDate = "2016-08-01",
                   minDate = "2015-08-01",
                   view = "months", #editing what the popup calendar shows when it opens
                   minView = "months", #making it not possible to go down to a "days" view and pick the wrong date
                   dateFormat = "yyyy-mm"
                   )

我刚刚使用的版本看起来像这样(灰色可能是我截取屏幕截图时光标悬停的位置)

example date picker showing only month