简体   繁体   中英

R Shiny - conditionalPanel and conditional values

My question is similar to this one: R studio shiny conditional statements

My ui.R looks something like this:

...
radioButtons("yes_or_no", "Yes or No?", c("yes"=1, "no"=0)),
  conditionalPanel(
    condition = "input.yes_or_no == '1'",
      numericInput("num_1", "First numeric input", 0, min=0),
      numericInput("num_2", "Second numeric input",0, min=0),
      numericInput("num_3", "Third numeric input",0, min=0)
  ),
...

I want the values num_1 , num_2 and num_3 equal 0 when the radioButton is set to "no" and the condition is not complied. And because ConditionalPanel is a 'graphical' condition only, it only affects the control widgets but not their values. According to the answer to this question ( R studio shiny conditional statements ) I realized the following in the server.R file:

yes_or_no <- input$yes_or_no
num_1 <- input$num_1
num_2 <- input$num_2
num_3 <- input$num_3

if (input$yes_or_no == 0) {
  num_1 <- 0
  num_2 <- 0
  num_3 <- 0
}
myfunction(yes_or_no, num_1, num_2, num_3)

But that does not work. When I enter values to the numericInputs they stay attached to them even if I set the conditionalPanel to "no" - my serverside if-statement does not overwrite these variables with 0.

Does anybody know, how to realize this? Thanks in advance!

Ok, with the help of the Shiny Google-Group I figured out how to do it. Here's a working example:

server.R:

library(shiny)
shinyServer(function(input, output) {

  output$ttable1 = renderTable({

    output$num_2_ui <- renderUI({
      num_2 <- ifelse(input$yes_or_no == 0, 0, input$num_2)
      numericInput("num_2", "Value num_2", value=num_2, min=0)
    })

    yes_or_no <- input$yes_or_no
    num_2 <- input$num_2

    table1 <- data.frame(yes_or_no, num_2)
    print(t(table1))

  })
})

ui.R:

library(shiny)

shinyUI(fluidPage(

  titlePanel("test"),

  sidebarLayout(
    sidebarPanel(
      uiOutput("num_2_ui"),
      radioButtons("yes_or_no", "Yes or No?", c("yes"=1, "no"=0), selected="no")

    ),

    mainPanel(
      uiOutput("ttable1")
    )
  )
))

Not sure if it's the only and best way, but for the moment it works for me.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM