Make the table interactive
Datatables from the DT
package are often a better way to display data in a Shiny app when compared to the built-in tables. Shiny tables can be converted to datatables with two simple code modifications: instead of using tableOutput()
and renderTable()
, you use DT::dataTableOutput()
and DT::renderDataTable()
. Datatables have a wide variety of customization options, but we will not be using any special options.
Note that with the DT
package, the convention is to not load the DT
package, and instead use the DT::
prefix when calling the datatable functions.
This exercise is part of the course
Case Studies: Building Web Applications with Shiny in R
Exercise instructions
The code for the Shiny app from the last coding exercise is provided without any modifications. Your task is to replace the basic Shiny table with a DT
table. Specifically:
- In the UI, replace the table output function with the
DT
datatable output (line 11). - In the server, replace the table rendering function with a
DT
datatable render function (line 31).
Hands-on interactive exercise
Have a go at this exercise by completing this sample code.
ui <- fluidPage(
h1("Gapminder"),
sliderInput(inputId = "life", label = "Life expectancy",
min = 0, max = 120,
value = c(30, 50)),
selectInput("continent", "Continent",
choices = c("All", levels(gapminder$continent))),
downloadButton("download_data"),
plotOutput("plot"),
# Replace the tableOutput() with DT's version
tableOutput("table")
)
server <- function(input, output) {
filtered_data <- reactive({
data <- gapminder
data <- subset(
data,
lifeExp >= input$life[1] & lifeExp <= input$life[2]
)
if (input$continent != "All") {
data <- subset(
data,
continent == input$continent
)
}
data
})
# Replace the renderTable() with DT's version
output$table <- renderTable({
data <- filtered_data()
data
})
output$download_data <- downloadHandler(
filename = "gapminder_data.csv",
content = function(file) {
data <- filtered_data()
write.csv(data, file, row.names = FALSE)
}
)
output$plot <- renderPlot({
data <- filtered_data()
ggplot(data, aes(gdpPercap, lifeExp)) +
geom_point() +
scale_x_log10()
})
}
shinyApp(ui, server)