【问题标题】:Shiny, reuss reactive input pickerInput闪亮的,reuss 反应式输入选择器输入
【发布时间】:2021-08-30 19:35:00
【问题描述】:

我正在尝试创建我的第一个闪亮的应用程序,但我遇到了一个困难:在下面的可重现示例中,我正在创建一个响应式选择器输入(即仅显示提出与访问者选择的输入相同的圆柱体的品牌)。

然后我希望基于 input_cylpicker_cny 的组合(请记住 picker_cny 取决于 input_cyl)显示一个表格,其中显示与 input_cyl 和 @ 组合匹配的观察的相关数据987654326@.

感谢您的帮助!

df <- mtcars
df$brand <- rownames(mtcars)
df$brand <- gsub("([A-Za-z]+).*", "\\1", df$brand)

if (interactive()) {

library(shiny)
library(shinyWidgets)
library(shinythemes)
library(shinycssloaders)

# Define UI -----------------------------------------------
ui <- fluidPage(
  
  # Application title
  titlePanel("Reproducible Example"),

  # Parameters
  sidebarLayout(
    sidebarPanel(
      selectInput(inputId = "input_cyl", label = "Cyl",
                  choices = c("6", "4", "8")),
      pickerInput(
        inputId = "picker_cny",
        label = "Select Company",
        choices = paste0(unique(df$brand)),
        options = list(`actions-box` = TRUE),
        multiple = TRUE),
      width = 2),
    
    # Show Text
    mainPanel(
      tableOutput("table"),
      width = 10)
  ))


# Define Server ------------------------------------------
server <- function(input, output, session) {
  
  # Reactive pickerInput ---------------------------------
  observeEvent(input$input_cyl, {
    
    df_mod <- df[df$cyl == paste0(input$input_cyl), ]
    
    # Method 1
    disabled_choices <- !df$cyl %in% df_mod$cyl
    updatePickerInput(session = session, 
                      inputId = "picker_cny",
                      choices = paste0(unique(df$brand)),
                      choicesOpt = list(
                        disabled = disabled_choices,
                        style = ifelse(disabled_choices,
                                       yes = "color: rgba(119, 119, 119, 0.5);",
                                       no = "")
                      ))
  }, ignoreInit = TRUE)
  
  output$table <- renderTable(df)
  }
} 


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

【问题讨论】:

    标签: r shiny


    【解决方案1】:

    您需要一个响应式来处理输入中的更改并在将数据帧提供给输出表之前对其进行子集化。为此,您只需将此块添加到您的服务器:

        data <- reactive({
            if (length(input$picker_cny) > 0)
                df[df$brand %in% input$picker_cny,]
            else 
                df
        })
    

    并像这样更新output$table

        output$table <- renderTable(data())
    

    注意:请随意删除反应中的if else 以获得:

        data <- reactive({
            df[df$brand %in% input$picker_cny,]
        })
    

    在这种情况下唯一的区别是:当尚未输入任何输入时,您是显示全部还是不显示。这是一个品味问题。

    【讨论】:

    • 谢谢亚历山大,它工作得很好!作为一个附带问题,如果我想为在picker_cny 中选择的内容分配一个ID,我可以执行choices = c(paste0(unique(df$brand)) = paste0(unique(df$brand_id))), 之类的操作。假设band_id是马自达等的唯一标识符
    猜你喜欢
    • 2020-08-01
    • 2020-07-04
    • 2017-11-24
    • 1970-01-01
    • 2021-07-16
    • 2018-10-09
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多