如何 enable/disable 一些输入基于 R Shiny 中的另一个输入?

How to enable/disable some inputs based on another in R Shiny?

我创建了一个代码,其中有 4 个数字输入,分别命名为滑块 1、2、3 和 4。滑块 1、2 和 3 已连接,这部分代码正在执行我想要的操作。但是,我想在 slider 0 的值等于 0 时禁用 slider 1、2 和 3,并在 slider0=1 时启用。 下面是一个可重现的例子:

library(shiny)

ui <- fluidPage(
  sidebarLayout(
    sidebarPanel(
      numericInput("slider0", "Slider 0: ", min = 0, max = 1, value = 1, step=1),
      numericInput("slider1", "Slider 1: ", min = 0, max = 1, value = 0.25, step=0.05),
      uiOutput("slider2"),
      uiOutput("slider3")),
    ))



server <- function(input, output) {
  output$slider2 <- renderUI({
    numericInput("slider2", "Slider 2", min = 0,  max = 1 - input$slider1, value = 0, step=0.05)
  }) 
  
  output$slider3 <- renderUI({
    numericInput("slider3", "Slider 3", min= 0, value = 1-input$slider1-input$slider2, max=1)
  })
  
  observeEvent(input$slider0, {
    if(input$slider0 == 0){
      shinyjs::disable("slider1")
    } else {
      shinyjs::enable("slider1")
    }
  })
  
  observeEvent(input$slider0, {
    if(input$slider0 == 0){
      shinyjs::disable("slider2")
    } else {
      shinyjs::enable("slider2")
    }
  })
  
  observeEvent(input$slider0, {
    if(input$slider0 == 0){
      shinyjs::disable("slider3")
    } else {
      shinyjs::enable("slider3")
    }
  })
  
}

runApp(list(ui = ui, server = server))

您可以使用 show/hide 并在 ui 中指定 useShinyjs()。此外,一名观察员就足够了。试试这个

library(shiny)
library(shinyjs)

ui <- fluidPage(
  sidebarLayout(
    sidebarPanel(
      useShinyjs(),
      #numericInput("slider0", "Slider 0: ", min = 0, max = 1, value = 1, step=1),
      radioButtons("slider0","Choose", choices = c("0" = "0", "1" = "1"), inline = TRUE),
      hidden(
      numericInput("slider1", "Slider 1: ", min = 0, max = 1, value = 0.25, step=0.05),
      uiOutput("slider2"),
      uiOutput("slider3"))
      ),
    mainPanel()
  ))

server <- function(input, output) {
  output$slider2 <- renderUI({
    req(input$slider1)
    numericInput("slider2", "Slider 2", min = 0,  max = 1 - input$slider1, value = 0, step=0.05)
  }) 
  
  output$slider3 <- renderUI({
    req(input$slider1,input$slider2)
    numericInput("slider3", "Slider 3", min= 0, value = 1-input$slider1-input$slider2, max=1)
  })
  
  observeEvent(input$slider0, {
    print(input$slider0)
    if(input$slider0 == "0"){
      shinyjs::hide("slider1")
      shinyjs::hide("slider2")
      shinyjs::hide("slider3")
    } else {
      shinyjs::show("slider1")
      shinyjs::show("slider2")
      shinyjs::show("slider3")
    }
  })
  
}

runApp(list(ui = ui, server = server))