簡體   English   中英

在 R Shiny 中將 selectInput 重置為 NULL

[英]Resetting selectInput to NULL in R Shiny

我需要能夠將 R Shiny 中的幾個 selectInput 小部件重置為它們的原始值 NULL(小部件中有一個空白文本區域)。 到目前為止,我得到了這樣的用戶輸入(哪個變量用作 x 軸):

  output$descrxaxis_Variable <- renderUI({
  selectInput(inputId = "descrxaxis", label = "Choose x axis variable", choices = colnames(descrDataMelted_selVars$df), multiple = TRUE)})

我正在使用這個獲取該變量的列索引:

 x_ind <- reactiveValues(val = NULL)
observeEvent(input$descrxaxis, {
  x_ind$val <- which(colnames(descrDataMelted_selVars$df) == input$descrxaxis)})

我需要做的是將 x_ind 重置為 NULL,這樣當用戶單擊“重置 X 軸”按鈕時,他們之前選擇的列就會消失。 這是我當前執行此操作的代碼:

    observeEvent(input$descrXaxisResetBtn, {
    updateSelectInput("descrxaxis", label = "Choose x axis variable", choices = colnames(descrDataMelted_selVars$df), multiple = TRUE, selected = NULL)})

但是,我也嘗試過:

  observeEvent(input$descrXaxisResetBtn, {
    shinyjs::useShinyjs()
    shinyjs::reset("descrxaxis")})

這些都不起作用,他們選擇的先前變量仍保留在小部件文本框中。 我如何讓它工作? 謝謝你。

編輯:這是有效的代碼(在回答我問題的人的幫助下)。

ui <- navbarPage(title = "SD Mesonet Quality Control", id = "navbarPage",
                     tabPanel(title = 'Metadata',
                              sidebarLayout(
                                sidebarPanel(width = 2,
                                             h4("Select Summary Variables to Plot"),
                                             div(style="display: inline-block; vertical-align:bottom; position:relative",
                                                 fluidRow(
                                                   column(10,
                                                          uiOutput("descrxaxis_Variable")),
                                                   column(2,
                                                          actionButton(inputId = "descrXaxisResetBtn", label = "Reset X", style = "padding:17px; color: #fff; background-color: #337ab7; border-color: #2e6da4"))
                                                 )
                                             ),        
                                             div(style="display: inline-block; vertical-align:bottom; position:relative",
                                                 fluidRow(
                                                   column(10,
                                                          uiOutput("descryaxis_Variable")),
                                                   column(2,
                                                          actionButton(inputId = "descrYaxisResetBtn", label = "Reset Y", style = "padding:17px; color: #fff; background-color: #337ab7; border-color: #2e6da4"))
                                                 )
                                             ),           
                                             div(style="display: inline-block; vertical-align:bottom; position:relative",
                                                 fluidRow(
                                                   column(10,
                                                          uiOutput("descrfacet_Variable")),
                                                   column(2,
                                                          actionButton(inputId = "descrFacetResetBtn", label = "Reset Facet", style = "padding:17px; color: #fff; background-color: #337ab7; border-color: #2e6da4"))
                                                 )
                                             ),        
                                             div(style="display: inline-block; vertical-align:bottom; position:relative",
                                                 fluidRow(
                                                   column(10,
                                                          uiOutput("descrcolor_Variable")),
                                                   column(2,
                                                          actionButton(inputId = "descrColorResetBtn", label = "Reset Color", style = "padding:17px; color: #fff; background-color: #337ab7; border-color: #2e6da4"))
                                                 )
                                             ),
                                             br(),
                                             actionButton("descrBtnPlot","Plot", style="color: #fff; background-color: #337ab7; border-color: #2e6da4")
                                             
                                ),
                                mainPanel(width = 10,
                                          plotlyOutput("descrSummaryStatsPlot")
                                )
                              )
                     )
    )
    
    server <- function(input,output,session){
      output$descrxaxis_Variable <- renderUI({
        selectInput(inputId = "descrxaxis", label = "Choose x axis variable", choices = colnames(descrDataMelted_selVars), multiple = TRUE, selected = character(0))})
      
      output$descryaxis_Variable <- renderUI({
        selectInput(inputId = "descryaxis", label = "Choose y axis variable", choices = colnames(descrDataMelted_selVars), multiple = TRUE)})
      
      output$descrfacet_Variable <- renderUI({
        selectInput(inputId = "descrfacet", label = "Choose facet variable", choices = colnames(descrDataMelted_selVars), multiple = TRUE)})
      
      output$descrcolor_Variable <- renderUI({
        selectInput(inputId = "descrcolor", label = "Choose color variable", choices = colnames(descrDataMelted_selVars), multiple = TRUE)})
      
      x_ind <- reactiveValues(val = NULL)
      observeEvent(input$descrxaxis, {
        x_ind$val <- which(colnames(descrDataMelted_selVars) == input$descrxaxis)})
      
      y_ind <- reactiveValues(val = NULL)
      observeEvent(input$descryaxis, {
        y_ind$val <- which(colnames(descrDataMelted_selVars) == input$descryaxis)})
      
      facet_ind <- reactiveValues(val = NULL)
      observeEvent(input$descrfacet, {
        facet_ind$val <- which(colnames(descrDataMelted_selVars) == input$descrfacet)})
      
      color_ind <- reactiveValues(val = NULL)
      observeEvent(input$descrcolor, {
        color_ind$val <- which(colnames(descrDataMelted_selVars) == input$descrcolor)})
      
      observeEvent(input$descrBtnPlot,{
        if (!is.null(x_ind$val) & !is.null(y_ind$val) & is.null(facet_ind$val) & is.null(color_ind$val)){
          p <- ggplot(descrDataMelted_selVars, aes_string(x = colnames(descrDataMelted_selVars)[x_ind$val], y = colnames(descrDataMelted_selVars)[y_ind$val])) + geom_point()}
        
        if (!is.null(x_ind$val) & !is.null(y_ind$val) & is.null(facet_ind$val) & !is.null(color_ind$val)){
          p <- ggplot(descrDataMelted_selVars, aes_string(x = colnames(descrDataMelted_selVars)[x_ind$val], y = colnames(descrDataMelted_selVars)[y_ind$val],
                                                          color = colnames(descrDataMelted_selVars)[color_ind$val])) + geom_point()}
        
        if (!is.null(x_ind$val) & !is.null(y_ind$val) & !is.null(facet_ind$val) & is.null(color_ind$val)){
          p <- ggplot(descrDataMelted_selVars, aes_string(x = colnames(descrDataMelted_selVars)[x_ind$val], y = colnames(descrDataMelted_selVars)[y_ind$val])) + geom_point() +
            facet_wrap(as.formula(paste("~",colnames(descrDataMelted_selVars)[facet_ind$val])))}
        
        if (!is.null(x_ind$val) & !is.null(y_ind$val) & !is.null(facet_ind$val) & !is.null(color_ind$val)){
          p <- ggplot(descrDataMelted_selVars, aes_string(x = colnames(descrDataMelted_selVars)[x_ind$val], y = colnames(descrDataMelted_selVars)[y_ind$val],
                                                          color = colnames(descrDataMelted_selVars)[color_ind$val])) + geom_point() +
            facet_wrap(as.formula(paste("~",colnames(descrDataMelted_selVars)[facet_ind$val])))}
        
        output$descrSummaryStatsPlot <- renderPlotly(p)
      })
      
      observeEvent(input$descrXaxisResetBtn, {
        updateSelectInput(session,"descrxaxis", selected = character(0))
      })
      
    }
    shinyApp(ui,server)

在前面,使用selected=character(0) (或selected="" ,正如@starja 評論的那樣):

    updateSelectInput("descrxaxis", label = "Choose x axis variable",
                      choices = colnames(descrDataMelted_selVars$df), multiple = TRUE, 
                      selected = character(0))

您的其他(重復)問題中的一些關鍵組件需要修復,並且與更新輸入的概念相關(但根據問題的當前 state 並不明顯):

  • 首先,不要將observeobserveEvent在另一個中。 這可能是您的代碼中的錯字,但請確保所有observe* (以及任何反應性 function,就此而言)功能有效地位於server function 的“頂層”。

    改變自

     observeEvent(input$descrBtnPlot,{... output$descrSummaryStatsPlot <- renderPlotly(p) observeEvent(input$descrXaxisResetBtn, { updateSelectInput("descrxaxis", selected = character(0)) }) })

     observeEvent(input$descrBtnPlot,{... output$descrSummaryStatsPlot <- renderPlotly(p) }) observeEvent(input$descrXaxisResetBtn, { updateSelectInput("descrxaxis", selected = character(0)) })

    (盡管這不完整,請參閱下一點)。

  • 其次,任何update* function 的第一個參數是session 這不是可選的。 上面第 1 條中的代碼實際上應該是

     observeEvent(input$descrBtnPlot,{... output$descrSummaryStatsPlot <- renderPlotly(p) }) observeEvent(input$descrXaxisResetBtn, { updateSelectInput(session, "descrxaxis", selected = character(0)) # ^^^^^^^^ the only difference })

    這讓我想到了最后一個項目符號:

  • 第三,你的server <- function(input, output)當你不使用任何update*功能時沒問題,但根據上面的第二點,你必須有session ,這意味着你需要將你的服務器定義更改為

    server <- function(input, output, session) {... }

我將使用?updateSelectInput中的示例來演示如何找到正確答案,但在實際調用之前注入單個browser()

library(shiny)

ui <- fluidPage(
  p("The checkbox group controls the select input"),
  checkboxGroupInput("inCheckboxGroup", "Input checkbox",
    c("Item A", "Item B", "Item C")),
  selectInput("inSelect", "Select input",
    c("Item A", "Item B", "Item C"))
)

server <- function(input, output, session) {
  observe({
    x <- input$inCheckboxGroup

    # Can use character(0) to remove all choices
    if (is.null(x))
      x <- character(0)

    browser()

    # Can also set the label and select items
    updateSelectInput(session, "inSelect",
      label = paste("Select input label", length(x)),
      choices = x,
      selected = tail(x, 1)
    )
  })
}

shinyApp(ui, server)
  1. 當您第一次運行它時,它將以一個空的選擇器開始,因此我們可以從該調試器中c

  2. Select 一個項目。 調用updateSelectInput設置selected = tail(x, 1) ,所以如果我們在控制台上運行它,我們會看到

    Browse[2]> tail(x, 1) [1] "Item A"

    c退出此調試器,注意選擇器現在Item A

  3. 取消選中“A”復選框,您將再次進入調試器。

     Browse[4]> tail(x, 1) character(0)

    c退出此調試器,您將看到選擇器現在為空(取消選擇)。

為什么? 在內部,查看updateSelectInput的源代碼(自 1.4.0.2 起),

updateSelectInput
# function (session, inputId, label = NULL, choices = NULL, selected = NULL) 
# {
#     choices <- if (!is.null(choices)) 
#         choicesWithNames(choices)
#     if (!is.null(selected)) 
#         selected <- as.character(selected)
#     options <- if (!is.null(choices)) 
#         selectOptions(choices, selected)
#     message <- dropNulls(list(label = label, options = options, 
#         value = selected))
#     session$sendInputMessage(inputId, message)
# }
# <bytecode: 0x00000000b8f06030>
# <environment: namespace:shiny>

看到它檢查的所有內容都是.is.null(selected) ,所以您使用selected=NULL的想法既是它的默認值,又被用作“不更改所選值”的選擇。


作為一個更具體的示例,我將從該應用程序的(非調試)版本開始,並添加一個“重置!” 按鈕將清除selectInput中的選擇:

ui <- fluidPage(
  p("The checkbox group controls the select input"),
  checkboxGroupInput("inCheckboxGroup", "Input checkbox",
    c("Item A", "Item B", "Item C")),
  selectInput("inSelect", "Select input",
    c("Item A", "Item B", "Item C")),
  actionButton("resetsel", "Reset!")
)

server <- function(input, output, session) {
  observe({
    x <- input$inCheckboxGroup

    # Can use character(0) to remove all choices
    if (is.null(x))
      x <- character(0)

    # Can also set the label and select items
    updateSelectInput(session, "inSelect",
      label = paste("Select input label", length(x)),
      choices = x,
      selected = tail(x, 1)
    )
  })

  observeEvent(input$resetsel, {
    ### either
    updateSelectInput(session, "inSelect", selected = character(0))
    ### or
    # updateSelectInput(session, "inSelect", selected = "")
    ### both do the same thing here
  })
}

shinyApp(ui, server)

現在,shiny 演示的基本操作有效,但是當您單擊重置按鈕時,選擇被清除。 僅供參考,如果您沒有更改choices= ,則無需將其包含在對updateSelectInput的調用中。 這沒有什么壞處,但只有當您認為可能需要更新/更改選項列表時才需要這樣做。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM