Search code examples
rdateshinyfiltering

Filtering by date in Shiny


cannot resolve a simple task as a poor Shiny guy.

I have a row in a data frame with dates

crime.date <- strptime(incidents$REPORT_DAT, format = "%Y-%m-%d") 

My output for dates looks like this.

[1] "2017-04-07 EDT" "2017-03-13 EDT" "2017-01-08 EST" "2017-01-25 EST" "2017- 
01-03 EST" "2017-01-03 EST" "2017-01-03 EST"
[8] "2017-01-03 EST" "2017-01-03 EST" "2017-01-03 EST" "2017-01-03 EST" "2017-
01-04 EST" "2017-01-03 EST" "2017-01-03 EST"

Now I try to visualize the selection of all crimes, chosen by this filter.

# USER INTERFACE CODE

ui <- fluidPage(
titlePanel("Washington, DC crimes by date"),

column(4, wellPanel(
dateRangeInput('dateRange',
               label = 'Filter crimes by date',
               start = crime.date , end = crime.date
)
)),
column(6,
     verbatimTextOutput("dateRange")
)
)

# SERVER CODE

server <- function(input, output, session) {
output$dateRangeText  <- renderText({
paste("input$dateRange is", 
      paste(as.character(input$dateRange), collapse = " to ")
)
})
}

shinyApp(ui = ui, server = server)

I believe that my mistake is somewhere between start and end because I put their only crime.date variable.

What do I want? I want to select start and end date and receive all incidents, which happened during this period (output as a text is fine for now).

Any help is MUCH APPRECIATED.

Thanks


Solution

  • To filter your dataframe, we can use the line

    incidents %>% filter(REPORT_DAT >= input$dateRange[1] & REPORT_DAT <= input$dateRange[2])
    

    within a renderDataTable statement. A working example is given below. Note that since you did not include sample data, I created some sample data myself.

    Hope this helps!


    enter image description here

    library(dplyr)
    library(shiny)
    
    # Sample data
    incidents = data.frame(REPORT_DAT=c('2018-01-01','2018-02-01','2018-03-01','2018-04-01','2018-05-01'))
    # Convert character to Date
    incidents$REPORT_DAT =  as.Date(incidents$REPORT_DAT, format = "%Y-%m-%d")
    
    ui <- fluidPage(
      titlePanel("Washington, DC crimes by date"),
    
      column(4, wellPanel(
        dateRangeInput('dateRange',
                       label = 'Filter crimes by date',
                       start = as.Date('2018-01-01') , end = as.Date('2018-06-01')
        )
      )),
      column(6,
             dataTableOutput('my_table')
      )
    )
    
    server <- function(input, output, session) {
      output$my_table  <- renderDataTable({
          # Filter the data
          incidents %>% filter(REPORT_DAT >= input$dateRange[1] & REPORT_DAT <= input$dateRange[2])
      })
    }
    
    shinyApp(ui = ui, server = server)