Filtering data.tables in shiny with 2 inputs

Ted Mosby Source

Code Below. I want to filter a data.frame based on two inputs. input$SelectGroup4 will be a column name in a data.frame and input$subsetSelect is a value in that column. Is this possible to do? Note: the whole code base is much much larger, so I took out only the key parts to this code. This code probably won't run on it's own, but it's just to get a general idea.

library(shiny)
library(data.table)
ui = fluidPage(
     uiOutput('textField'),
     uiOutput('docIdField'),
     fluidRow(column(4,textInput("keyword", "Enter keyword :", "WB")),
                      fluidRow(column(4, sliderInput("context", "Enter number of words for context :",
                                                     min = 1, max = 10,
                                                     value = 5))),
     fluidRow(column(4,uiOutput('selectGroup4'))),
     fluidRow(column(4,uiOutput('subsetSelect'))),
     fluidRow(column(10,DT::dataTableOutput("kwicTable"))))
}

    server = function(input,output){
        df_corpus1 <- reactive({
              dTemp = as.data.table(datasetInput())
              dTemp = dTemp %>% filter(input$selectGroup4==input$subsetSelect)

            })

          output$kwicTable=renderDataTable({
            dtemp = df_corpus1()
            dtemp = corpus(as.data.frame(dtemp),text_field=input$textField,docid_field=input$docIdField)
            x = kwic(x = dtemp,pattern=input$keyword,window=input$context)
            x = as.data.table(x)
            x[,4:6]
          })
    }

shinyApp(ui,server)
rshinydata.table

Answers

answered 6 months ago Florian #1

Yes, you can do that. Since we do not have access to your dataset, here is a working example with the mtcars dataset.

Hope this helps!

library(shiny)

ui <- fluidPage(
  selectInput('col','Column',colnames(mtcars)),
  uiOutput('ui_col'),
  dataTableOutput('table')
)

server <- function(input,output){

  # Create a new input element with the unique values of the selected column
  output$ui_col <- renderUI({
    req(input$col)
    selectizeInput('val','Value',unique(mtcars[[input$col]]),multiple=T)
  })

  # If both inputs are not null, filter the table
  output$table <- renderDataTable({
    df <- mtcars
    if(!is.null(input$col) & !is.null(input$val))
    {
     df = df[df[[input$col]] %in% input$val,]
    }
    df
  })

}

shinyApp(ui = ui, server = server)

comments powered by Disqus