使用 conditionalPanel 时错误的 renderText 输出(闪亮)

Wrong renderText output on use of conditionalPanel (shiny)

我在根据条件面板中的输入呈现输出时遇到问题。下面我编写了我的代码的修改版本,其中我删除了所有与问题无关的额外内容。

ui.R是

library(shiny)

shinyUI(fluidPage(

titlePanel("Art and R"),

sidebarLayout(
    sidebarPanel(

        selectInput(
            "colspa", "Color space", choices = list("A" = "a", "B" = "b"), selected = 1
        ),  

        conditionalPanel(
            condition = "input.colspa == 'a'", selectInput(
                "colchoice", "Color choice", choices = list("ONE" = "one", "TWO" = "two", "THREE" = "three"), selected = 1
            )
        ),

        conditionalPanel(
            condition = "input.colspa == 'b'", selectInput(
                "colchoice", "Color choice", choices = list("FOUR" = "four", "FIVE" = "five", "SIX" = "six"), selected = 1
            )
        ),

        actionButton("btn", "Show!")
    ),

    mainPanel(
        textOutput("distPlot")
    )
)
))

而 server.R 是

library(shiny)

shinyServer(function(input, output) {
str2 <<- ""
str3 <<- ""
getResults1 <- observeEvent(input$btn, {
    str2 <<- (paste0(input$colspa))
})

getResults2 <- observeEvent(input$btn, {
    str3 <<- (paste0(input$colchoice))
})

calculate <- eventReactive(input$btn, {
    str1 <<- paste0(str2, str3)
    return(str1)
})

output$distPlot <- renderText({
    calculate()
})
})

如果我 运行 这个应用程序,当 colspa 是 "a" 时,我会得到正确的结果,但是一旦我从 selectInput 将 colspa 更改为 "b" ,渲染的输出不是我想要的。下面是问题的一个例子。

您不应为两个不同的输出使用相同的 ID。失败的原因是 "colchoice" 仍然绑定到第一个 selectInput,因为它与第二个具有相同的 ID。以下是 updateSelectInput 的工作示例。请注意,为此您需要在服务器中添加一个额外的 session 参数。

ui <- shinyUI(fluidPage(

  titlePanel("Art and R"),

  sidebarLayout(
    sidebarPanel(
      # first select input
      selectInput(
        "colspa", "Color space", choices = list("A" = "a", "B" = "b"), selected = "a"
      ),
      # second select input 
      selectInput(
          "colchoice", "Color choice", choices = list("ONE" = "one", "TWO" = "two", "THREE" = "three"), selected = "one"
      ),

      actionButton("btn", "Show!")
    ),

    mainPanel(
      textOutput("distPlot")
    )
  )
))

server <- shinyServer(function(input, output, session) {

  # change choices of input$colchoice depending on input$colspa
  observeEvent(input$colspa, {
    if(input$colspa == "a") myChoices <- c("ONE" = "one", "TWO" = "two", "THREE" = "three")
    else myChoices <- c("FOUR" = "four", "FIVE" = "five", "SIX" = "six")

    updateSelectInput(session, "colchoice", choices = myChoices)
  })


  # display selected choices upon click of input$btn

  calculate <- eventReactive(input$btn, {
    paste0(input$colspa, input$colchoice)
  })

  output$distPlot <- renderText({
    calculate()
  })
})
shinyApp(ui, server)