我想创建一个闪亮的应用程序,其中两个slideinputs加起来为100.这意味着,如果用户更改了一个滑块的值,另一个滑块会自动更改以满足约束(100-input $ slider1)。
我在这里发现了类似的问题: Examplecode
使用以下代码:
服务器
library(shiny)
# Define server logic required
shinyServer(function(input, output) {
output$slider2 <- reactiveUI(function() {
sliderInput("slider2", "Slider 2", min = 0, max = 100 - input$slider1, value = 0)
})
output$restable <- renderTable({
myvals<- c(input$slider1, input$slider2, 100-input$slider1-input$slider2)
data.frame(Names=c("Slider 1", "Slider 2", "Slider 3"),
Values=myvals)
})
})
UI:
library(shiny)
# Define UI for application
shinyUI(pageWithSidebar(
# Application title
headerPanel("Sliders should sum to 100!"),
# Sidebar with sliders whos sum should be constrained to be 100
sidebarPanel(
sliderInput("slider1", "Slider 1: ", min = 0, max = 100, value = 0, step=1),
uiOutput("slider2")
),
# Create table output
mainPanel(
tableOutput("restable")
)
))
这已经是一个没问题的解决方案。但是这里只能更改滑块1以获得滑块2的自动更改。另一方面,如果用户更改滑块2,则滑块1不适合约束。 我怎样才能让人们可以改变两个滑块以使另一个适合约束?
答案 0 :(得分:3)
我为第二个
添加了一个双updateSliderInput
和renderUI
rm(list = ls())
library(shiny)
ui <-pageWithSidebar(
# Application title
headerPanel("Sliders should sum to 100!"),
# Sidebar with sliders whos sum should be constrained to be 100
sidebarPanel(
sliderInput("slider1", "Slider 1: ", min = 0, max = 100, value = 0, step=1),
uiOutput("slider")),
# Create table output
mainPanel(tableOutput("restable"))
)
server <- function(input, output,session) {
observe({
updateSliderInput(session, "slider1", min =0,max=100, value = 100 - input$slider2)
})
output$slider <- renderUI({
sliderInput("slider2", "Slider 2: ", min=0,max=100, value=100 - input$slider1)
})
output$restable <- renderTable({
myvals<- c(input$slider1, input$slider2, 100-input$slider1-input$slider2)
data.frame(Names=c("Slider 1", "Slider 2", "Slider 3"),Values=myvals)
})
}
runApp(list(ui = ui, server = server))