R Shiny:仅用于月份和年份的 dateRangeInput

问题描述 投票:0回答:2

有没有办法在 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 = " - ")

我想要的是在选择日期时删除这一步:

enter image description here

r shiny date-range
2个回答
16
投票

我刚刚使用

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


9
投票

看看下面这个自定义函数

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

© www.soinside.com 2019 - 2024. All rights reserved.