Search code examples
shinynumeric-input

R shiny: test numericInput by using logical operator


In the shiny app a number can be entered (numericInput). A method should make sure that if the number equals to 1 it stays 1, but in all other cases (x!=1) the variable has to be set to 0.

in server.r:

...    
checkNumber=reactive({
      if(!is.null(input$data)){    

      output$n_insertNumber<-renderUI({
        if(!is.null(input$data)){
          numericInput("number", "Number", value = 8)
        }  
      })

      x<-input$number
      if (x!=1){x==0}
      }
})
...

in ui.r:

...    
uiOutput("n_insertNumber"),
...

Output:

Warning: Error in if: argument is of length zero

Can someone help me to find a solution? Thanks!


Solution

  • In this example app you can input a number with numericInput widget which then goes to the server and within a reactive environment a test is made. Its result is either 1 or 0 and is accessible via Variable().


    library(shiny)
    
    ui <- shinyUI(fluidPage(
    
       titlePanel("Example"),
    
       sidebarLayout(
          sidebarPanel(
             numericInput("number", "Number", value = 8)
          ),
    
          mainPanel(
             verbatimTextOutput("n_insertNumber")
          )
       )
    ))
    
    server <- shinyServer(function(input, output) {
    
      Variable <- reactive({
        ifelse(test = input$number == 1, yes = 1, no = 0)
      })
    
       output$n_insertNumber <- renderPrint({
         Variable()
       })
    })
    
    
    shinyApp(ui = ui, server = server)