How to set an initial value for two dependent input values (Slider and Numeric) in shiny?

假如想象 提交于 2019-12-08 04:20:03

问题


I have achieved to define two interconnected or mutually dependent input in my shiny app. Right now, my problem is to set a specific initial value for these slider and numeric inputs. It seems that they always start with the minimum value, even I don't now exactly why. How can I indicate a unique starting point or an initial value for these input parameters?

I have attached a simplified part of my app in order to provide you a reproducible version of my problem here:

"ui.R"

library(shiny)

shinyUI(fluidPage(

  uiOutput("Param_s"),
  uiOutput("Param_n")

))

and the "server.R"

library(shiny)

shinyServer(
function(input,output) {

# Mutually dependent  slider and numeric inputs 
output$Param_s = renderUI({
  sliderInput(inputId = "param_slide",
            label= "My input parameter",
            value= input$param_numeric,
            min=1,
            max=200)
 })

output$Param_n = renderUI({
  numericInput(inputId = "param_numeric",
             label= "My input parameter",
             value= input$param_slide,
             min=1,
             max=200)
})


})

I tried various things to fix the initial value but eventually nothing worked. Any help would be appreciated!!


回答1:


wow! I got it guys! You should only update the two input objects at the same time and up to the same value. It means adding these two lines solved my problem to set the initial value to 60 for example:

updateSliderInput(session,"param_slide", value = 60)
updateNumericInput(session,"param_numeric", value = 60 )

Therefore the whole "server.R" would be like this:

#
library(shiny)

shinyServer(
function(input,output,session) {

# Mutually dependent  slider and numeric inputs 
output$Param_s = renderUI({
sliderInput(inputId = "param_slide",
            label= "My input parameter",
            value= input$param_numeric,
            min=1,
            max=200)
})

output$Param_n = renderUI({
numericInput(inputId = "param_numeric",
             label= "My input parameter",
             value= input$param_slide,
             min=1,
             max=200)
})

updateSliderInput(session,"param_slide", value = 60)
updateNumericInput(session,"param_numeric", value = 60 )

})

You should only be aware of adding these updates with an

observeEvent()

when you have these input objects on the other tabs. In my case which I am using "sidebarMenu" I used a simple line of code as this:

observeEvent(input$sidebar_id =="tab1",{
  updateSliderInput(session,"param_slide", value = 60)
  updateNumericInput(session,"param_numeric", value = 60 )
})


来源:https://stackoverflow.com/questions/54634020/how-to-set-an-initial-value-for-two-dependent-input-values-slider-and-numeric

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!