Is it possible to return the output of an if statement to use as a filter in shiny?

Solution 1:

We can use .data[[]] pronoun to subset with a string.

The app should look something like this.

library(shiny)
library(tidyverse)

ui <- fluidPage(
  selectInput("type", "Type", choices = c("type_a", "type_b", "type_c")),
  actionButton("run_calcs")
)

server <- function(input, output, session) {
  results <- eventReactive(input$run_calcs, {
    if (input$calc_type == "Monthly Average") {
      results <- data_filtered() %>%
        mutate(ymd(week)) %>%
        mutate(monthly_calc = format(as.Date(week), "%B %Y")) %>%
        group_by(monthly_calc) %>%
        summarize(n = sum(.data[[input$type]]))
    }
  })
}

shinyApp(ui, server)