Add a table output
In order to add any output to a Shiny app, you need to:
- Create the output (plot, table, text, etc.).
- Render the output object using the appropriate
render___
function. - Assign the rendered object to
output$x
. - Add the output to the UI using the appropriate
___Output
function.
In this exercise, you will add a table output to the baby names explorer app you created earlier. Don't forget that code inside a render___
function needs to be wrapped inside curly braces (e.g. renderPlot({...})
).
This exercise is part of the course
Building Web Applications with Shiny in R
Exercise instructions
- Create a table output named
table_top_10_names
, with top 10 most popular names by sex and year. You can use the functiontop_10_names()
to generate a data frame to display. - Display the table in the UI.
Hands-on interactive exercise
Have a go at this exercise by completing this sample code.
ui <- fluidPage(
titlePanel("What's in a Name?"),
# Add select input named "sex" to choose between "M" and "F"
selectInput('sex', 'Select Sex', choices = c("F", "M")),
# Add slider input named "year" to select year between 1900 and 2010
sliderInput('year', 'Select Year', min = 1900, max = 2010, value = 1900)
# CODE BELOW: Add table output named "table_top_10_names"
)
server <- function(input, output, session){
# Function to create a data frame of top 10 names by sex and year
top_10_names <- function(){
babynames %>%
filter(sex == input$sex) %>%
filter(year == input$year) %>%
slice_max(prop, n = 10)
}
# CODE BELOW: Render a table output named "table_top_10_names"
}
shinyApp(ui = ui, server = server)