I am attempting to use an if statement as a way to return a column name that will be selected in an interactive shiny app to return a monthly average of the selected column's stats. I have attempted to use input$type, case_when, ifelse, and base R if statements -- is there a better strategy for referring to an unknown column name in shiny?
filtering <- if('Type A' %in% input$type){
filtering = c("type_a")
} else if('Type B %in% input$type){
filtering = c("type_b")
} else if('Type C %in% input$type){
filtering = c("type_c")
} else {
filtering = "Nothing"
}
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(filtering))
}
})
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)