hartmut
hartmut

Reputation: 982

shiny dateRange input - set constraints on the range

A question concerning dateRangeInput.

I am aware of the min/max, start/end parameters.

I need to put a constraint on the range that is given, viz. on the difference end-start. Specifically, I give the user the possibility of computing a rolling average, and need to make sure that there are at least 6 months between start and end.

How can I achieve this please?

(There is a way to have inputs depend on one another (see answer to this question). Here however, we want the datarangeInput[1] to depend upon daterangeInput[2]... but these two are not quite separate.)

EDIT: comments below pretty much answer the question as originally phrased (see below). For the code to be entirely satisfactory however, how can you make sure that the input range is corrected by the server BEFORE other computations that depend upon that input range are themselves started? With my existing solution (see below), the observer will correct the value too late: calculations based on the faulty range already started by that time

Upvotes: 1

Views: 1023

Answers (1)

hartmut
hartmut

Reputation: 982

Following BigDataScientist's and Mike Wise's comments, I adapted this answer to solve the issue. The result is a server code that makes sure that the range resulting from the daterangeInput is longer than a given value (here, smallestWindow).

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

mindate <- "1980-01-01"
maxdate <- Sys.Date()
smallestWindow <- 18 * 31
from <- maxdate - smallestWindow

ui <- fluidPage(
  mainPanel(uiOutput("slider"))
)

server <- function(input, output, session) {
  observeEvent(input$timeperiod,{
    if(input$timeperiod[1] > (input$timeperiod[2] - smallestWindow)){
      updateDateRangeInput(session, "timeperiod", start=input$timeperiod[2] - smallestWindow)
    }
  })

  output$slider <- renderUI({
    dateRangeInput("timeperiod", "Time Period:"
                   , min=as.Date(mindate), max=maxdate
                   , start = from , end = maxdate)
  })

}
shinyApp(ui, server)

Upvotes: 3

Related Questions