开发sliderInput的最小值/最大值的无功更改

时间:2015-02-10 09:07:06

标签: r render shiny dplyr

感谢这个solution我终于想出了如何创建动态SliderInput按钮。不幸的是,我毕竟使用此input值时遇到问题(更改dplyr中的子集条件)。谁能告诉我我做错了什么?

ui.R

library(dplyr)
library(shiny)
library(ggvis)

shinyUI(fluidPage(

titlePanel("Old Faithful Geyser Data"),

# Sidebar with a slider input for number of bins
sidebarLayout(
sidebarPanel(
  radioButtons("dataset", label = h4("Product level"),
               choices = list("Item" = "df1", "Task" = "df2")),
  uiOutput("slider")
  ),
mainPanel(
  ggvisOutput("plot")
   )
 )
))

server.R

 library(shiny)
 library(dplyr)

 df1 <- data.frame(id = c(1,2,3,4,5), number = c(20,30,23,25,34))
 df2 <- data.frame(id = c(1,2), number = c(33,40))

 shinyServer(function(input, output) {

 datasetInput <- reactive({
   switch(input$dataset,
         df1 = df1,
         df2 = df2)
 })

 output$slider <- renderUI({
   sliderInput("inslider","Slider", min   = min(datasetInput()$number), 
                                   max   = max(datasetInput()$number),
                                   value = c(min(datasetInput()$number),     
                                             max(datasetInput()$number))
 })
 data <- reactive({
  datasetInput %>%
    filter(number >= input$inslider[1],
           number <= input$inslider[2])
 })

 vis <- reactive({
  data %>%
   ggvis(~id, ~number) %>%
   layer_points(fill = ~factor(id)) %>%
   scale_nominal("fill", range = c("red","blue","green","yellow","black"))

 })
 vis %>% bind_shiny("plot") 
})

1 个答案:

答案 0 :(得分:2)

由于您使用renderUI制作滑块,因此在过滤数据之前必须检查input$inslider是否存在。当您第一次加载它时,它不会因为它是由renderUI

创建的

试试server.R

library(shiny)
library(dplyr)

df1 <- data.frame(id = c(1,2,3,4,5), number = c(20,30,23,25,34))
df2 <- data.frame(id = c(1,2), number = c(33,40))

shinyServer(function(input, output) {

  datasetInput <- reactive({
    switch(input$dataset,
           "df1" = df1,
           "df2" = df2)
  })

  output$slider <- renderUI({
    sliderInput("inslider","Slider", min   = min(datasetInput()$number), 
                max   = max(datasetInput()$number),
                value = c(min(datasetInput()$number),     
                          max(datasetInput()$number))
  )})


  data <- reactive({
    filteredData<-datasetInput()
    if(!is.null(input$inslider)){
      filteredData<-filteredData %>%
      filter(number >= input$inslider[1] ,
             number <= input$inslider[2] )
    }
    filteredData
    })

  vis <- reactive({

    data()%>%
      ggvis(~id, ~number) %>%
      layer_points(fill = ~factor(id)) %>%
      scale_nominal("fill", range = c("red","blue","green","yellow","black"))

  })
  vis %>% bind_shiny("plot") 

})