This code-through shows how to build interactive tables in R using the DT package. DT wraps the JavaScript DataTables library and lets you sort, search, filter, paginate, and export tables with very little code.
We will:
By the end, you will be able to:
We will use the traffic accidents dataset from the Tempe Open Data Portal (Tempe, Arizona).
For simplicity, we’ll use these variables in our tables:
DT_cols <- c("Incidentid", "Year", "StreetName","Totalinjuries", "Totalfatalities", "Lightcondition", "Weather")
dt <- dat %>% select(all_of(DT_cols))
head(dt)
Install and load the DT package:
Use datatable() to turn a data frame into an interactive table (we’ll use dt):
Show filter boxes for each column at the top of the table using filter = “top”:
Use pageLength (default rows shown) and lengthMenu (dropdown choices). - -1 means “All rows”.
datatable(
dt,
filter = "top",
options = list(pageLength = 10,
lengthMenu = list(c(5, 10, 25, 50, 100, -1),
c("5", "10", "25", "50", "100", "All"))
#-1 is a special value meaning “All rows”
))Display intuitive headers without changing the underlying data frame column names using colnames
intuitive_names <- c(
"Incident ID","Year","Street Name",
"Total Injuries","Total Fatalities",
"Light Condition","Weather"
)
datatable(
dt,
colnames = intuitive_names,
filter = "top",
options = list(
pageLength = 10,
lengthMenu = list(
c(5, 10, 25, 50, 100, -1),
c("5", "10", "25", "50", "100", "All")
)
)
)Below are some widely used DataTables extensions available through DT.
datatable(
dt,
colnames = intuitive_names,
filter = "top",
extensions = c("Buttons", "ColReorder", "KeyTable", "FixedHeader"),
options = list(
dom = "Bfrtip",
buttons = c("copy", "csv", "excel", "pdf", "print"),
pageLength = 10,
lengthMenu = list(c(5, 10, 25, 50, 100, -1),
c("5", "10", "25", "50", "100", "All")),
colReorder = TRUE,
keys = TRUE,
fixedHeader = TRUE
)
)
Here’s a compact, well-configured table combining custom column names, filters, export buttons, column reordering, fixed header, and keyboard navigation:
datatable( # create an interactive DataTable
dt, # the data frame to display
colnames = intuitive_names, # custom column headers
filter = "top", # filter boxes at the top of each column
extensions = c("Buttons", "KeyTable", "FixedHeader"),
options = list(
dom = "Bfrtip", # layout: Buttons + filter + table + info + pagination
buttons = c("copy", "csv", "excel", "pdf", "print"), # export/copy buttons
pageLength = 10, # show 10 rows
lengthMenu = list( # rows-per-page dropdown choices
c(5, 10, 25, 50, 100, -1),
c("5", "10", "25", "50", "100", "All")
),
colReorder = TRUE, # drag columns to reorder
keys = TRUE, # arrow-key navigation
fixedHeader = TRUE # keep header visible while scrolling
)
)