Add a select input
Adding an input to a shiny app is a two step process, where you first add an ___Input(“x”)
function to the UI and then access its value in the server using input$x
.
For example, if you want users to choose an animal from a list, you can use a selectInput
, and refer to the chosen value as input$animal
:
selectInput(
'animal',
'Select Animal',
selected = 'Cat',
choices = c('Dog', 'Cat')
)
In this exercise, you will build a Shiny app that lets users visualize the top 10 most popular names by sex by adding an input to let them choose the sex.
This exercise is part of the course
Building Web Applications with Shiny in R
Exercise instructions
- Add a select input named "sex" to let users choose between "M" and "F", with a default of "F".
- Update server code to get the top 10 names for the chosen sex instead of "F" only.
Hands-on interactive exercise
Have a go at this exercise by completing this sample code.
ui <- fluidPage(
titlePanel("What's in a Name?"),
# CODE BELOW: Add select input named "sex" to choose between "M" and "F"
# Add plot output to display top 10 most popular names
plotOutput('plot_top_10_names')
)
server <- function(input, output, session){
# Render plot of top 10 most popular names
output$plot_top_10_names <- renderPlot({
# Get top 10 names by sex and year
top_10_names <- babynames %>%
# MODIFY CODE BELOW: Filter for the selected sex
filter(sex == "F") %>%
filter(year == 1900) %>%
slice_max(prop, n = 10)
# Plot top 10 names by sex and year
ggplot(top_10_names, aes(x = name, y = prop)) +
geom_col(fill = "#263e63")
})
}
shinyApp(ui = ui, server = server)