I am trying to create an app that loads a csv into a table and then allows filtering by specific conditions that are triggered by click events on checkboxes and a htmlwidget. I can filter by the click event but the initial dataframe is not loaded. How can I resolve this issue? A very minimal kind of example is shown below:
library(shiny)
library(dplyr)
library(DT)
ui <- fluidPage(
checkboxInput("filter1", "A filter"),
DTOutput("table")
)
server <- function(input, output, session) {
data <- reactive({ mtcars}) # this reads file input but I am using mtcars as substitute
output$table <- DT::renderDT({DT::datatable(filter_1())})
filter_1 <- reactive({
req(input$filter1)
# I want to load the CSV data in the table and then upon clicking on a widget or
# checkbox only then should a given filter be applied
if (is.null(input$filter1)) {data()} else {data() %>% filter(mpg > 25)}
})
}
shinyApp(ui, server)
CodePudding user response:
req
checks if a value is "truthy". filter1
is initialised with FALSE
which is not "truthy", therefore the code for filter_1
is not executed. Only if you tick the checkbox, its value is TRUE
and the data is shown. This means that in the if
clause you need to check for TRUE
/FALSE
, not NULL
.
In the example, you don't need req
. To be on the safe side, you could explicitly check if filter1
is not NULL
to not show weird error messages to the user during startup.
library(shiny)
library(dplyr)
library(DT)
ui <- fluidPage(
checkboxInput("filter1", "A filter"),
DTOutput("table")
)
server <- function(input, output, session) {
data <- reactive({ mtcars}) # this reads file input but I am using mtcars as substitute
output$table <- DT::renderDT({DT::datatable(filter_1())})
filter_1 <- reactive({
req(!is.null(input$filter1))
# I want to load the CSV data in the table and then upon clicking on a widget or
# checkbox only then should a given filter be applied
if (input$filter1) {data() %>% filter(mpg > 25)} else {data()}
})
}
shinyApp(ui, server)