我在根据条件面板中的输入渲染输出时遇到问题。下面我已经编写了我的代码的修改版本,其中删除了与问题无关的所有额外内容。
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")
)
)
))
服务器.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”,所呈现的输出就不是我想要的。以下是问题的一个例子。
答案 0 :(得分:1)
您不应对两个不同的输出使用相同的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)