使用 Shiny 选择列、相等、值来按条件过滤

Use Shiny to choose column, equality, and value to filter by conditions

我正在创建一个闪亮的应用程序,我希望用户能够在其中 select 列和条件,从而生成可用于过滤数据框的 input$COLUMN input$CONDITION input$VALUE

期望的输出

iris %>% filter(input$COLUMN input$CONDITION input$VALUE) == iris %>% filter(Sepal.Length > 4.7)

为此,我需要为 input$COLUMN 使用 rlang,我需要 eval input$CONDITION,我需要将 input$VALUE 转换为适当时使用数字。 (我正在 verbatimTextOutput 中尝试这样做)

实现此目标的最佳方法是什么?我认为将整个表达式变成一个在整洁的管道中解析的字符串可能是可行的方法,但我愿意接受其他建议!!

library(shiny)
library(tidyverse)


ui <- fluidPage(

   # Sidebar with an input for column
   # boolean input
   # and value input
   sidebarLayout(
      sidebarPanel(
        fluidRow(column(4, selectInput("COLUMN", "Filter By:", choices = colnames(iris))),
                 column(4, selectInput("CONDITION", "Boolean", choices = c("==", "!=", ">", "<"))),
                 column(4, uiOutput("COL_VALUE")))
      ),

      # Show text generated by sidebar
      # use text in tidy pipeline to create subsetted dataframe
      mainPanel(
         verbatimTextOutput("as_text"),
         tableOutput("the_data")
      )
   )
)

# Define server logic required to draw a histogram
server <- function(input, output) {

  output$COL_VALUE <- renderUI({
    x <- iris %>% select(!!sym(input$COLUMN))
    selectInput("VALUE", "Value", choices = x)
  })

  filtering_string <- reactive ({
    paste0("!!sym(", input$COLUMN, ") ", input$CONDITION, " ", input$VALUE)
  })

   output$as_text <- renderText({
     filtering_string()
   })


   output$the_data <- renderTable({
     iris %>%
       eval(parse(text = filtering_string()))
   })
}

# Run the application 
shinyApp(ui = ui, server = server)


我不太熟悉 !!sym 但你可以这样做:

  output$the_data <- renderTable({

    # To hide error when no value is selected
    if (input$VALUE == "") {
      my_data <- "" 
    } else {
      my_data <- iris %>% 
        filter(eval(parse(text = paste0(input$COLUMN, input$CONDITION, input$VALUE))))  
    }

    return(my_data)

  })