首页 > 解决方案 > 从 selectInput 到 facet_wrap 的多个变量:R Shiny

问题描述

我正在使用 facet_wrap() 为我的 Shiny App 寻求帮助。我有一些数据,我希望应用程序使用从单个 selectInput 中选择的一个或多个变量动态 facet_wrap。应用程序只使用一个变量而不是多个变量。当我从同一个 selectInput 中选择多个变量时,图中只考虑第一个变量进行分面。我不想使用 facet_grid()。有两件事我需要帮助。

  1. 当应用程序第一次启动时,我收到错误“错误:第一个参数无效”。如何摆脱这个错误。
  2. 如何使用从单个 selectInput 中选择的多个变量来刻面图。非常感谢任何建议或帮助。

重复代码:

library(shiny)
library(tidyverse)
library(DT)
# Define UI for data upload app ----
ui <- fluidPage(
    titlePanel("Upload & View Files"),
      sidebarLayout(
        sidebarPanel(width = 2,
          selectInput("facet", "Select Facets", choices = colnames(data), "", multiple = T)
  ),
    
    # Main panel for displaying outputs ----
    mainPanel("Data View",
      plotOutput("heatmap", width = "1050px", height = "800px"),
      DT::dataTableOutput("table")
      
    )
    
  )
)

# Define server logic to read selected file ----
server <- function(session, input, output) {
  data <- diamonds
   output$table  <- DT::renderDataTable(data, options = list(paging = T, pageLength = 20))
   output$heatmap <- renderPlot({
     ggplot(data, aes(x = carat, fill = carat)) + geom_bar() + facet_wrap(~ get(input$facet), scales = "free")
   })
  }
shinyApp(ui, server)

我看到的是从 selectInput 中选择多个变量时;例如:切工、净度、深度等。facet_wrap(~ cut + clarity + depth, scales = "free)

需要多方面的错误消息

标签: rshinyfacet-wrapselectinput

解决方案


要删除错误,请使用req(). 对于多个选定的变量,一种方法如下所示。可能有更好的方法来做到这一点。

output$heatmap <- renderPlot({
    req(input$facet)
    
    facets <- input$facet %>% 
      str_replace_all(",", "+") %>% 
      rlang::parse_exprs()
    
    ggplot(data, aes(x = carat, fill = carat)) + geom_bar() +
      facet_wrap(vars(!!!facets), scales = "free")
    
  })

输出


推荐阅读