R Shiny: Using numeric output variable as the initial value of slider

Viewed 29

My shiny app looks like this:

library(shiny)
library(shinydashboard)

ui <- dashboardPage(
  dashboardHeader(title = "Basic dashboard"),
  dashboardSidebar(),
  dashboardBody(
    
    fluidRow(
      box(plotOutput("plot1", height = 250)),
      
      box(textInput("my_text",  # supposed to be a numeric input
                    "Text input:"),
        title = "Controls",
        sliderInput("slider",
                    "Number of observations:",
                    min = 1, max = 100,
                    value = 50 # Want it to be output$my_init
                    )
      )
    )
  )
)

server <- function(input, output) {
  set.seed(122)
  histdata <- rnorm(500)
  
  output$plot1 <- renderPlot({
    data <- histdata[seq_len(input$slider)]
    hist(data)
  })
  
# My attempt
# output$my_init <- input$my_text + 28
}

shinyApp(ui, server)

I want to set the initial value of the slider as output$my_init, a numeric variable that will be the result of operating some input variables. I tried using renderPrint, but the output is not numeric.

Thanks in advance.

1 Answers

I piggybacked on @stefan's comments and came up with this answer:

library(shiny)
library(shinydashboard)

ui <- dashboardPage(
  dashboardHeader(title = "Basic dashboard"),
  dashboardSidebar(),
  dashboardBody(
    
    fluidRow(
      box(plotOutput("plot1", height = 250)),
      
      box(numericInput("my_num", "Numeric input:", value = 50),
          title = "Controls",
          sliderInput("slider",
                      "Number of observations:",
                      min = 1, max = 100,
                      value = 50 # Want it to be output$my_init
          )
      )
    )
  )
)

server <- function(input, output) {
  set.seed(122)
  histdata <- rnorm(500)
  
  output$plot1 <- renderPlot({
    data <- histdata[seq_len(input$slider)]
    hist(data)
  })
  
  # My attempt
  observeEvent(input$my_num, {
    updateSliderInput(inputId = "slider", value = input$my_num)
  })
}

shinyApp(ui, server)

The idea is to use observeEvent() to trigger updateSliderInput() (update slider input widget) and update the value parameter of sliderInput()

Related