【发布时间】:2020-07-06 11:09:34
【问题描述】:
我希望shiny 应用程序的用户从数据库中查询和过滤数据。用户应该能够灵活地应用可选过滤器,这意味着不应该处理未使用的过滤器(即没有输入值的过滤器)。以下代码完成了工作。但是,服务器功能有些混乱。该代码使用两个if (...) {...} else {...} 块。我想知道是否有更简单、更简洁的方法来实现这一点。
# Libraries
library(shiny)
library(dplyr)
library(DT)
library(RSQLite)
library(DBI)
# Example database
con <- DBI::dbConnect(RSQLite::SQLite(), path = ":memory:")
copy_to(con, mtcars, "mtcars", temporary = FALSE)
# User interface
ui <- fluidPage(
textInput(inputId = "input_vs", label = "vs",
value = "", placeholder = "Please select one value: 0, 1"),
textInput(inputId = "input_carb", label = "carb",
value = "", placeholder = "Please select one value: 1, 2, 3, 4, 5, 6, 8"),
# Eingabe: Start-Knopf
actionButton(inputId = "go", label = "Start"),
DT::dataTableOutput("output_data")
)
# Server function
server <- function(input, output){
# Query data
data <- eventReactive(input$go, {
x <- tbl(con, "mtcars")
if (input$input_vs != "") { x <- x %>% filter(vs == !!input$input_vs) } else { x <- x }
if (input$input_carb != "") { x <- x %>% filter(carb == !!input$input_carb) } else { x <- x }
x <- x %>% show_query() %>% collect()
})
output$output_data <- renderDataTable({ data() })
}
# Start shiny app
shinyApp(ui, server)
是否可以在dplyr 管道中使用类似if (...) {...} else {...} 的东西?仅当用户提供输入值时才应处理过滤器。从某种意义上说:
# Does not work
x <- tbl(con, "mtcars") %>%
if (input$input_vs != "") { filter(vs == !!input$input_vs) %>% }
if (input$input_carb != "") { filter(carb == !!input$input_carb) %>% }
show_query() %>%
collect()
请注意,我知道在此示例中,文本输入不是最明智的选择,例如,单选按钮会更有意义。然而,在我的现实生活示例中,文本输入是明智的。
【问题讨论】:
-
看起来这可能会对您有所帮助。 community.rstudio.com/t/…
-
感谢您的链接,我可以编写一个可以在 dplyr 管道中使用的函数。但是,在闪亮的应用程序中使用它会导致错误(“错误:无效参数类型”)。我怀疑该错误与范围界定有关,但我不确定。