Add a continent selector: select input
When there are many options to let the user choose from, radio buttons can take up a lot of space and may not be ideal. Select inputs—also called 'dropdown lists'—can also be used to ask the user to choose an option from a list of choices, but in a more compact way. With a select input, all the options appear in a scrollable list, so it can be used even if you have many choices.
Similar to radio buttons, select inputs also have choices
and selected
parameters. Additionally, select inputs have a multiple
argument, which, when set to TRUE
, allows the user to select more than one value.
The code for the Shiny app from the last exercise is provided with slight modifications.
Cet exercice fait partie du cours
Case Studies: Building Web Applications with Shiny in R
Instructions
- Add a
selectInput()
to the UI with ID "continents" and a label of "Continents", with the default continent set to "Europe".- The choices in the list should be all the different continents that exist in the gapminder dataset.
- Allow the user to select multiple continents simultaneously.
- Add code to the server such that only data for the selected continent is shown, by subsetting the gapminder dataset (line 23).
Exercice interactif pratique
Essayez cet exercice en complétant cet exemple de code.
ui <- fluidPage(
sidebarLayout(
sidebarPanel(
textInput("title", "Title", "GDP vs life exp"),
numericInput("size", "Point size", 1, 1),
checkboxInput("fit", "Add line of best fit", FALSE),
radioButtons("color", "Point color",
choices = c("blue", "red", "green", "black")),
# Add a continent dropdown selector
___(___, ___,
choices = levels(___),
multiple = ___,
selected = ___)
),
mainPanel(
plotOutput("plot")
)
)
)
# Define the server logic
server <- function(input, output) {
output$plot <- renderPlot({
# Subset the gapminder dataset by the chosen continents
data <- subset(gapminder,
___ %in% ___$continents)
p <- ggplot(data, aes(gdpPercap, lifeExp)) +
geom_point(size = input$size, col = input$color) +
scale_x_log10() +
ggtitle(input$title)
if (input$fit) {
p <- p + geom_smooth(method = "lm")
}
p
})
}
shinyApp(ui = ui, server = server)