感谢这个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")
})
答案 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")
})