是否可以 return if 语句的输出用作闪亮的过滤器?

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

我正在尝试使用 if 语句来 return 将在交互式闪亮应用程序中选择的列名称 return 所选列统计数据的月平均值。我尝试使用 input$type、case_when、ifelse 和 base R if 语句——是否有更好的策略来引用闪亮的未知列名?

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))
  }
})

我们可以使用 .data[[]] 代词对字符串进行子集化。

该应用程序应如下所示。

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)