I have a relatively complex app that I am building and I want users to drag coupled sliders to set the weights for some calculations. These should always sum to 100%. I looked at this and that but I have real problems with reactivity and isolation and the updateslider option seems to work for up two sliders.
So instead, I transposed the problem. I will message the user that the weights need to sum to 100% if they don't and show the example plotoutput if they do. Simples right? Well, no, as the conditions are not conforming. After looking at this and this and this, I cannot get it to work.
I provide a reproducible example below to demonstrate this problem - I suspect it's because of my awkwardness with reactivity and observers in shiny.
library(shiny)
# Define UI for application that draws a histogram
ui <- fluidPage(
# Application title
titlePanel("testing 1 2 3"),
# Sidebar with a slider input for number of bins
sidebarLayout(
sidebarPanel(
),
# Show a plot of the generated distribution
mainPanel(
fluidRow(
column(width = 2,
offset = 0,
align = "center",
sliderInput(inputId = "sld_1",
label = "weight",
min = 0,
max = 1,
value = 0.25,
step = 0.05,
animate = TRUE)
,
sliderInput(inputId = "sld_2",
label = "weight",
min = 0,
max = 1,
value = 0.25,
step = 0.05,
animate = TRUE)
,
sliderInput(inputId = "sld_3",
label = "weight",
min = 0,
max = 1,
value = 0.25,
step = 0.05,
animate = TRUE)
,
sliderInput(inputId = "sld_4",
label = "weight",
min = 0,
max = 1,
value = 0.25,
step = 0.05,
animate = TRUE)
) #slider columns
,
column(width = 9,
offset = 0,
align = "center",
conditionalPanel(
condition = "output.myCondition == FALSE",
textOutput(outputId = "distPrint")
) #conditional1
,
conditionalPanel(
condition = "output.myCondition == TRUE",
plotOutput(outputId = "distPlot")
) #conditional2
) #column
)#fluidrow
)
)
)
# Define server logic required to draw a histogram
server <- function(input, output,session) {
dister <- reactive({
if( !is.null(input$sld_1) &&
!is.null(input$sld_2) &&
!is.null(input$sld_3) &&
!is.null(input$sld_4) &&
sum(input$sld_1,input$sld_2,input$sld_3,input$sld_4)==1
) {
rnorm(input$sld_1*1000)
} else {c(0,1,2,3,4,5)}
})
output.myCondition <- reactive({
if( !is.null(input$sld_1) &&
!is.null(input$sld_2) &&
!is.null(input$sld_3) &&
!is.null(input$sld_4) &&
sum(input$sld_1,input$sld_2,input$sld_3,input$sld_4)==1
) {
TRUE
} else {FALSE}
})
output$distPlot <- renderPlot({
x<-dister()
hist(x)
})
output$distPrint <- renderText({
print("The weights must sum to 100%")
})
}
# Run the application
shinyApp(ui = ui, server = server)