R Shiny:如何使输入值有条件地被动(在另一个输入上)?

时间:2016-09-07 19:54:13

标签: r reactive-programming shiny

我希望应用程序使用默认值加载一次,但只有在用户键入正确的密码时才会变为被动。为了简单起见,让我们使用Rstudio模板(经过精心编辑):

ui.R

library(shiny)

shinyUI(fluidPage(  
   sidebarLayout(
      sidebarPanel(              
          passwordInput("pw", "Password:"),

          sliderInput("nbins",
                      "Number of bins:",
                      min = 1,
                      max = 50,
                      value = 30)
      ),    
    mainPanel(
    plotOutput("histo")
    )
)))

server.R

PASSWORD <- "test"

library(shiny)

shinyServer(function(input, output) {

    output$histo <- renderPlot({
        x    <- faithful[, 2]
        bins <- seq(min(x), max(x), length.out = input$nbins + 1)
        hist(x, breaks = bins, col = 'darkgray', border = 'white')
    })
})

有两个被动输入pwnbins。我的问题是:如何扩展代码以使nbins(行为)在被动非被动之间切换,具体取决于输入pw等于PASSWORD

2 个答案:

答案 0 :(得分:1)

这个解决方案怎么样:

PASSWORD <- "test"

    library(shiny)

    shinyServer(function(input, output) {
            bins <- eventReactive(input$nbins, {
                    if (input$pw == PASSWORD) {
                    bins <- seq(min(faithful[, 2]), max(faithful[, 2]), length.out = input$nbins + 1) 
                    } else {
                    bins <- seq(min(faithful[, 2]), max(faithful[, 2]), length.out = 30 + 1)      
                    }
            })

            output$histo <- renderPlot({
                    x <- faithful[, 2]                       
                    hist(x, breaks = bins(), col = 'darkgray', border = 'white')
            })
    })

答案 1 :(得分:0)

根据Valter的回答,您可以使用shinyjs启用/禁用与输入窗口小部件的交互。

<强> ui.R

library(shiny)
library(shinyjs) # install shinyjs

shinyUI(fluidPage(  
  useShinyjs(), # activate
  sidebarLayout(
    sidebarPanel(              
      passwordInput("pw", "Password:"),

      sliderInput("nbins",
                  "Number of bins:",
                  min = 1,
                  max = 50,
                  value = 30)
    ),    
    mainPanel(
      plotOutput("histo")
    )
  )))

<强> server.R

library(shiny)
library(shinyjs)

shinyServer(function(input, output) {

  observe({
    if(input$pw != "PASSWORD") shinyjs::hide("nbins") else shinyjs::show("nbins")
  })

  output$histo <- renderPlot({
    x    <- faithful[, 2]

    # will 'reset' bins to original value if incorrect pw
    if(input$pw != "PASSWORD") {
      bins <- seq(min(x), max(x), length.out = 30 + 1)
    } else {
      bins <- seq(min(x), max(x), length.out = input$nbins + 1)
    }

    hist(x, breaks = bins, col = 'darkgray', border = 'white')
  })
})