问题
I have written the following R Shiny app. The user selects farm from a drop-down menu and a single value of year from a slider. I would like the user to be able to select a range of values for month, but the second slider is only selecting the end points of month, not the range.
Here is what the month slider is selecting, as an example with farm == 1 and year == 2 from the data.frame fruit created within the app below:
> fruit[fruit$farm == 1 & fruit$year == 2 & fruit$month %in% c(4,9),]
farm year month apples cherries
16 1 2 4 70.23774 82.18512
21 1 2 9 38.99675 66.07546
Here is what I would like the month slider to select:
> fruit[fruit$farm == 1 & fruit$year == 2 & fruit$month %in% c(4:9),]
farm year month apples cherries
16 1 2 4 70.23774 82.18512
17 1 2 5 37.17340 83.47027
18 1 2 6 36.00925 73.27322
19 1 2 7 31.20337 98.30440
20 1 2 8 33.93355 63.92046
21 1 2 9 38.99675 66.07546
How can I modify this code so all selected months are included in the resulting plot? Here is my Shiny app:
library(shiny)
set.seed(1234)
n.farms <- 5
n.years <- 3
fruit <- data.frame(
farm = rep(1:n.farms, each = 12*n.years),
year = rep(rep(1:n.years, each = 12), n.farms),
month = rep(1:12,n.farms * n.years),
apples = runif(n.farms*12*n.years, 20, 80),
cherries = runif(n.farms*12*n.years, 0, 100)
)
ui <- fluidPage(
titlePanel("Subset and Plot Fruit Data"),
sidebarLayout(
sidebarPanel(
selectInput("codeInput1", label = "Choose Farm", choices = unique(fruit$farm)),
sliderInput("codeInput2", label = "Select Year",
min = min(fruit$year), max = max(fruit$year),
value = median(fruit$year), step = 1),
sliderInput("codeInput3", label = "Select Month Range",
min = min(fruit$month), max = max(fruit$month),
value = unique(fruit$month)[c(4,9)], step = 1)
),
mainPanel(
plotOutput("view")
)
)
)
server <- function(input, output) {
dataset <- reactive({
return(subset(fruit, (farm == input$codeInput1 &
year == input$codeInput2 &
month %in% input$codeInput3)))
})
output$view <- renderPlot(plot(dataset()$apples, dataset()$cherries))
}
shinyApp(ui = ui, server = server)
回答1:
If you select a range, sliderInput returns the minimum and the maximum, but not all values in this range. So you have to generate the range from the two returned values:
month %in% (input$codeInput3[1]:input$codeInput3[2])
Edit
As Mark points out, my solution only works for integers; the correct way to test for a range (with included borders) is:
month >= input$codeInput3[1] && month <= input$codeInput3[2]
来源:https://stackoverflow.com/questions/62265345/shiny-app-with-two-sliders-second-slider-is-only-selecting-the-endpoints-not-r