Using the Datatable DT Package

Leah Coffin

November 18, 2023

DT Package

DT, short for datatable, is a useful package when one wants to include widgets within their html data table. To get started you will need to make sure that you have DT added to your package library. If you do not, go to Tools, Install Packages and type/select DT, or install.packages(DT). Once installed you can add it to your library code chunk, as below.

library(tidycensus)
library(tidyverse)
library(DT)
data("USArrests")

Useful table

DT produces an interactive data table with HTML widget to adjust the number of entries the user can view and a a search box. For example, using the data set USArrests, you can adjust how many states you see by10, 25, or 50. If you want to find a specific state quickly, use the search bar. Try searching “New York” in the table.

When you want to view the full data set again, clear the search bar.

datatable(USArrests)

Ordering data in your table

Another helpful tool you can use with DT is the ordering. The default setting for the USArrests dataset is to order alphabetically by US state.
Using the arrow widgets for each column in this package it is easy to order a selected column in ascending or descending order. If you want to order your table using two or more variables, use order function, as below.

datatable(USArrests, options = list(
  order = list(list(2, 'asc'), list(3, 'desc'))
))

De-identify row names

If you are using data in which you do not want to identify the row names (in this instance, state names), you can hide the names using the argument rownames=FALSE or you can assign each row name a letter using rownames=LETTERS , as I have done below.

datatable(head(USArrests), rownames = head(LETTERS))

Add a caption

Lastly, we can add a caption to the table to describe what the table displays using the caption argument. Placing a caption directly in the table provides helpful information for the user.

datatable(USArrests, caption="Violent crime rates by US state per 100,000 residents and percent of population living in urban areas.")

Acknowledgements

For further assistance and more tricks with DT, please explore DT: An R interface to the DataTables library

This site for prettydoc was also extremely useful prettydoc: Creating pretty documents from R markdown