Search code examples
rshinyshinydashboarddt

Filter DataTable Output based on unique observations


Below is a code to my shiny app

library(shiny)

DF = data.frame(ID = c ("1","2","3","4","5"),
                product = c("A","B","C","A","C"),
                sentiment = c("good","medium","bad","medium","bad"),
                online = c(1,0,1,1,0),
                ooh = c(0,1,0,1,1),
                Date= c("2020-08-11", "2020-09-16","2021-10-20", "2020-11-25", "2022-11-27"), 
                event = c(1,1,0,0,0))



# Define UI for application that draws a histogram
ui <- fluidPage(
  
  # Application title
  titlePanel("Product Sentiment"),
  
  # Sidebar with a slider input for number of bins 
  sidebarLayout(
    sidebarPanel(
      selectInput("selectsentiment", label = "Select sentiment", choices = unique(DF$sentiment)), 
      dateRangeInput("daterange", h5("Date range"), 
                     start = ymd("2020-08-11"), 
                     end = ymd("2022-09-06"), 
                     min = min(DF$Date), 
                     max = max(DF$Date),
                     format = "yyyy-mm-dd"
      ) 
    ),
    
    # Show a plot of the generated distribution
    mainPanel(
      dataTableOutput("DT_Table")
    )
  )
)

# Define server logic required to draw a histogram
server <- function(input, output) {
  
  output$DT_Table <- renderDataTable({ 
    DF[DF$sentiment %in% input$selectsentiment,]
    
  })   
  
}

# Run the application 
shinyApp(ui = ui, server = server)

I want to filter the output of the datatable when a person does both. I.e. selecting positive or negative as well as selecting a date date range How do I go about that?


Solution

  • Please check the updated renderDataTable call:

    library(shiny)
    
    DF = data.frame(ID = c ("1","2","3","4","5"),
                    product = c("A","B","C","A","C"),
                    sentiment = c("good","medium","bad","medium","bad"),
                    online = c(1,0,1,1,0),
                    ooh = c(0,1,0,1,1),
                    event = c(1,1,0,0,0))
    
    
    
    
    # Define UI for application that draws a histogram
    ui <- fluidPage(
      
      # Application title
      titlePanel("Product Sentiment"),
      
      # Sidebar with a slider input for number of bins 
      sidebarLayout(
        sidebarPanel(
          selectInput("selectsentiment", label = "Select sentiment", choices = unique(DF$sentiment))
        ),
        
        # Show a plot of the generated distribution
        mainPanel(
          dataTableOutput("DT_Table")
        )
      )
    )
    
    # Define server logic required to draw a histogram
    server <- function(input, output) {
      
      output$DT_Table <- renderDataTable({ 
        DF[DF$sentiment %in% input$selectsentiment,]
      })   
      
    }
    
    # Run the application 
    shinyApp(ui = ui, server = server)