我正在R中构建一个闪亮的应用程序,其中我在顶部有一个多个复选框来过滤因子的级别。然后,我会显示过滤数据的各种表格/图表。然而,在Shiny中,我只知道如何通过重新过滤每个反应中的整个数据集来过滤每个反应。例如,
数据集>筛选器>构建表1
数据集>筛选器>构建表2
数据集>筛选器>构建表N
相反,为了提高效率,我希望有一种只运行一次过滤器的方法。例如
数据集>筛选器>构造表1。。。,N.
这可能吗?我给出了一个使用mtcars
的小示例代码,并从过滤后的多个复选框中只创建了一个图和一个表。
#install.packages(c("shiny", "shinythemes", "shinyjs", "plotly", "shinydashboard"))
library(shiny)
library(shinythemes)
library(shinyjs)
library(plotly)
library(shinydashboard)
data(mtcars)
ui <- dashboardPage(skin = "blue",
dashboardHeader(title = "Stack Overflow Example"),
sidebar = dashboardSidebar(),
dashboardBody(
fluidRow(
box(width = 12,
checkboxGroupInput(inputId = "checkgroup",
label = "Engine to show:",
choices = c("V-shaped" = "0",
"Straight" = "1"),
selected = c("0","1")))),
fluidRow(
box(plotlyOutput(outputId = "plot_weight", height = "240"),
shiny::tableOutput("table_weight")
)
)
)
)
server <- function(input, output) {
# Subset data
selected_data <- reactive({
mtcars_checkgroup <- mtcars %>% filter(vs %in% c((input$checkgroup)))
return(mtcars_checkgroup)
})
table_weight <- reactive({
selected_data() %>%
summarise(mean(wt))
})
plot_weight <- reactive({
ggplot(selected_data(), aes(y = wt)) + geom_boxplot()
})
output$table_weight <- shiny::renderTable({(table_weight())}, striped = TRUE)
output$plot_weight <- renderPlotly({plot_weight()})
}
shinyApp(ui, server)
我看了一下其他问题,比如在闪亮的R中过滤反应数据集,但每次用户更新时,这仍然会重新运行过滤器
如有任何帮助,我们将不胜感激。谢谢
在您的代码中,过滤器只运行过一次:在selected_data <- reactive({...})
中。shine将自动缓存您的selected_data()
,以便在所有输出中使用。
此外,您可能希望通过不对输出使用反应式中间语句来简化代码:
output$table_weight <- renderTable(selected_data() %>%
summarise(mean(wt)), striped = TRUE)
output$plot_weight <- renderPlotly(ggplot(selected_data(), aes(y = wt))
+ geom_boxplot())