This post explains how display R data object (such as dataframe)
as HTML pages with filtering,
editing and even use
callback javascript functions with the
DT package. It provides several reproducible examples
with explanation and R code.
We showcase the
key features of DT and provides a
set of table examples using the package.
{DT}
The DT package is an interface for the
DataTable JavaScript library in R. It can be used for
rendering interactive and dynamic tables in
R Markdown documents and Shiny web
applications.
It (mainly) offers a datatable() function that creates an
HTML widget that display a table. This table is
interactive and dynamic thanks to the use of JavaScript.
✍️ author → Yihui Xie
📘 documentation → github
⭐️ more than 500 stars on github
To get started with DT, you can install it directly from
CRAN using the install.packages function:
Using DT is straightforward. It provides a
datatable() function. You just have to provide a
dataframe to this function and that’s it, you get the interactive
table!
Here’s a basic example:
library(DT)
data(mtcars)
table = datatable(mtcars)
table
# save the widget
# library(htmlwidgets)
# saveWidget(table, file="../HtmlWidget/dt-table-basic.html")
In the datatable() function, there is a
cell argument that can take CSS classes. The available
ones are: display, cell-border,
compact hover, nowrap,
order-column, row-border,
stripe.
Example using cell-border, stripe,
hover and compact:
library(DT)
table = datatable(
mtcars,
class = 'cell-border stripe hover compact'
)
table
# save the widget
# library(htmlwidgets)
# saveWidget(table, file="../HtmlWidget/dt-table-1.html")
Thanks to the caption argument and the
htmltools library, you can add customized caption to
the table.
Example:
library(DT)
library(htmltools)
data(mtcars)
table <- datatable(
mtcars,
caption = tags$caption(
style = 'caption-side: bottom; text-align: center;',
'Table 1: ', em('The mtcars dataset is a dataset about cars properties')
)
)
table
# save widget
# library(htmltools)
# saveWidget(table, file="../HtmlWidget/dt-table-2.html")
The datatable() function has a filtering option.
Depending on the type of variable, the filtering might differ: -
quantitative columns: range slider -
qualitative columns: select from all possible
categories
Example:
library(DT)
data(mtcars)
table <- datatable(mtcars,
filter = "top", # put filters on top of the table
)
table
# save widget
# library(htmltools)
# saveWidget(table, file = "../HtmlWidget/dt-table-3.html")