Change output to shiny only when I change the value in numericInput()

Question:

I have this table in my shiny app.

| a | 2 |
| b | 3 |
| c | 5 |

There is a box to choose a line (from 1 to 3), and from that it prints the value referring to that line.

There's also another box so I can change this value. But the numericInput() function asks for an initial value, so when I select a line it already changes the output to the initial value.

But I want this value to change only if I change the value in the numericInput() . I can set the initial value to a negative value and put an if() but I don't want it that way.


Here's the example:

library('shiny')

ui <- fluidPage(

  numericInput('line', 'Line Choice:', value = 1, min = 1, max = 3),
  numericInput('number', 'Value Choice:', value = 0),
  textOutput('text')

)

server <- function(input, output) {
  observe({

    df <- data.frame(c('a', 'b', 'c'), c(2, 3, 5))

    output$text <- renderText({

      i <- input$line
      df[i,2] <- input$number

      paste0(df[i,1], ': ', df[i, 2])

    })
  })

}
shinyApp(ui, server)

Thanks

Answer:

You can generate this numericInput on the server side so you can determine what the initial value should be. Example:

library('shiny')

ui <- fluidPage(

  numericInput('line', 'Line Choice:', value = 1, min = 1, max = 3),
  uiOutput("number_ui"),
  textOutput('text')

)

server <- function(input, output) {

    df <- data.frame(c('a', 'b', 'c'), c(2, 3, 5))


    output$number_ui <- renderUI({
      numericInput('number', 'Value Choice:', df[input$line, 2])
    })

    output$text <- renderText({
      i <- input$line
      if(!is.null(input$number))
        df[i,2] <- input$number
      paste0(df[i,1], ': ', df[i, 2])
    })

}
shinyApp(ui, server)

More details in this article

Scroll to Top