更新sliderInput in Shiny reactively

时间:2016-11-29 10:37:41

标签: r shiny

我正在尝试动态更改sliderInput的值。现在的困难在于我想要从具有一个值的sliderInput更改为具有范围的sliderInput,这似乎不起作用。

下面代码中的第一个操作按钮有效,而第二个操作按钮不符合要求。

是否唯一可能切换到uiOutput元素?

代码

library(shiny)
app <- shinyApp(
   ui = bootstrapPage(
      sliderInput("sld1", min = 0, max = 10, label = "y1", value = 5),
      actionButton("acb1", "Change Value"),
      actionButton("acb2", "Change Value to Range")
   ),
   server = function(input, output, session) {
      observeEvent(input$acb1, {
         updateSliderInput(session, "sld1", value = 2)
      })
      observeEvent(input$acb2, {
         updateSliderInput(session, "sld1", value = c(2,7))
      })
   })
runApp(app)

1 个答案:

答案 0 :(得分:4)

您可以使用renderUI

动态添加滑块
#rm(list = ls())
library(shiny)
app <- shinyApp(
  ui = bootstrapPage(
    uiOutput("myList"),
    actionButton("acb1", "Change Value"),
    actionButton("acb2", "Change Value to Range")
  ),
  server = function(input, output, session) {

    slidertype <- reactiveValues()
    slidertype$type <- "default"

    observeEvent(input$acb1,{slidertype$type <- "normal"})
    observeEvent(input$acb2, {slidertype$type <- "range"})

    output$myList <- renderUI({

      if(slidertype$type == "normal"){
        sliderInput("sld1", min = 0, max = 10, label = "y1", value = 2)
      }
      else if(slidertype$type == "range"){
        sliderInput("sld1", min = 0, max = 10, label = "y1", value = c(2,7))
      }
      else{
        sliderInput("sld1", min = 0, max = 10, label = "y1", value = 5)
      }
    })    
})
runApp(app)