4.1 DT: Datatables

One of the easiest interactive visualizations to create in R is an interactive datatable, which you can create using the DT package (Xie, Cheng, and Tan 2018Xie, Yihui, Joe Cheng, and Xianying Tan. 2018. DT: A Wrapper of the Javascript Library ’Datatables’. https://CRAN.R-project.org/package=DT.). If you went through the “Prerequisites”, you should have installed that package to your computer. You can scroll down to see one example. Explore this table a little bit. You’ll see that you can click the numbers at the bottom right of the table to page through all the data in the table. You can use the arrows beside the column names to rearrange the rows based on the values they have in a column. With the search box in the top right, you can try searching for specific elements in the data.25 As an example, try searching for “2017-09-10” in the search box to get the accidents that occurred on the day of Hurricane Irma’s Florida landfall, September 10, 2017. Then try clicking on the “fatals” column name until the arrow beside it points down, to see what the maximum number of fatalities during an accident was.

You can build this table using the DT package in the htmlwidgets family of packages. First, you need to read in the data you’d like to print. We’re using one of the datasets from the “Plot” section, so you can read it in the same way you did in the previous section (if you already have readr and magrittr loaded from working on a previous section, you can skip those lines):

library("readr")

fl_accidents <- read_csv("data/fl_accidents.csv") 

Now, to print this dataframe as an interactive data table, just run the data frame through the datatable function.

library("magrittr")
library("DT")
fl_accidents %>% 
  datatable()

In your R Studio session, the interactive table should show up in the “Viewer” pane. If you want to see it in a separate window, click on the “Zoom” button, and it will open the table in a separate window that you can rescale.

You can do a lot of customization through the datatable call. For example, you can add a caption to the table, change the appearance using the class parameter, change the table width, and use clearer names for the columns. Try the following example code to see an example of how these changes can change the table’s appearance:

datatable(fl_accidents, 
          class = "compact", 
          caption = "Example of an interactive data table. Each observation (row) is the information for one of the fatal motor vehicle accidents in Florida the week of Hurricane Irma's landfall, with columns for the county where the accident occurred, the date of the accident, and the number of fatalities.",
          colnames = c("County FIPS", "Date",
                       "Latitude", "Longitude", "# fatalities"),
          width = 800)

To get more details on all the options available, see the helpfile for datatable (run ?datatable) or read through the online tutorial for the package.