Learn how to build attractive data tables with R packages
Published in · 8 min read · Oct 7, 2022
--
Developing meaningful visualizations is an essential yet challenging task in data science. Along with the correct choice of tools, a general understanding of the target audience and the goal of the analysis is also expected in any data analysis. In the same context, tables are a powerful and efficient way of organizing and summarizing any available dataset, especially containing categorical variables. Tables are often used in reports along with supporting data visualizations to communicate the results of data analysis effectively. With some relevant narrative text, tables can precisely share the analysis findings for decision-making in an organization. Although Data visualization in R is a vast topic in itself due to the availability of several robust and easy-to-use plotting libraries, the same can be said about tables in R. The CRAN website offers many open-source packages for R users. These packages can not just create tables but also transform the basic tables into beautiful tables that effectively communicate the analysis findings.
In this article, we will discuss seven interesting packages for building colorful tables in R.
Several R packages offer features to create nicely structured tables. Here are a few packages we’ll use to create beautiful tables.
- gt (License: MIT)
The gt package offers a different and easy-to-use set of functions that helps us build display tables from tabular data. The gt philosophy states that a comprehensive collection of table parts can be used to create a broad range of functional tables. These are the table body, the table footer, the spanner column labels, the column labels, and the table header. Below is an illustration of the gt package’s architecture:
The output formats that gt currently supports are HTML, LaTeX, and RTF. You can find more about gt here. For installing the gt package from CRAN, use the following command:
install.packages(“gt”)
For installing the development version of gt from GitHub, use the following commands:
devtools::install_github(“rstudio/gt”)
Next, we will import the gt library package.
library(gt)
Let’s take the mtcars dataset from the pre-installed datasets of R. This dataset was extracted from the Motor Trend US Magazine (1974) and consists of information on the fuel consumption along with 10 attributes of automotive design and performance of 32 cars (1973 and 1974 models). We can print the first few rows of the ‘mtcars’ dataset using the following command:
head(mtcars)
Next, we create a new dataframe df using the first few columns and rows from the dataset mtcars.
We will call the main function “gt” with our newly created dataframe “df.” The table will appear on your default browser or the Viewer panel if you use RStudio or another R GUI.
df %>%gt()
The table we created is a simple table, as the formatting properties used are the default properties. The default appearance of the tables can be changed by using the tab_style()
function, through which we can target specific cells and apply styles to them.
df %>%gt() %>%
tab_header(title = “mtcars dataset”) %>%
tab_style(
style = list(cell_fill(color = “#b2f7ef”),
cell_text(weight = “bold”)),
locations = cells_body(columns = mpg))%>%
tab_style(
style = list(cell_fill(color = “#ffefb5”),
cell_text(weight = “bold”)),
locations = cells_body(columns = hp))
2. formattable (License: MIT + file LICENSE):
Formattable data frames are data frames that will be displayed in HTML tables using formatter functions. This package includes techniques to produce data structures with predefined formatting rules, such that the objects maintain the original data but are formatted. The package consists of several standard formattable objects, including percent, comma, currency, accounting, and scientific. You can find more about formattable here.
For installing the formattable package from CRAN, use the following command:
install.packages(“formattable”)
For installing the development version of formattable from GitHub, use the following commands:
devtools::install_github(“renkun-ken/formattable”)
Next, we will import the formattable library package.
library(formattable)
To demonstrate this library, we will use the built-in function color_bar()
to compare the magnitude of values in given columns of data.
formattable(df, list(
hp = color_bar(“#e9c46a”),
cyl = color_bar(“#80ed99”),
wt = color_bar(“#48cae4”),
disp = color_bar(“#f28482”)))
3. kableExtra (License: MIT + file LICENSE)
The kableExtra package is used to extend the basic functionality of knitr::kable tables()
. Although knitr::kable()
is simple by design, it has many features missing which are usually available in other packages, and kableExtra has filled the gap nicely for knitr::kable().
The best thing about kableExtra is that most of its table capabilities work for both HTML and PDF formats. You can find more about kableExtra here.
For installing the kableExtra package from CRAN, use the following command:
install.packages(“kableExtra”)
For installing the development version of kableExtra from GitHub, use the following commands:
remotes::install_github(“haozhu233/kableExtra”)
Next, we will import the kableExtra library package.
library(kableExtra)
We will call the kbl function with dataframe “df” to view the basic version of the table.
kable(df) %>% kable_styling(latex_options = “striped”)
To style individual rows and columns, we can use the functions row_spec()
and column_spec()
.
df %>% kbl() %>%
kable_paper() %>% column_spec(2, color = “white”,
background = spec_color(mtcars$drat[1:2],end = 0.7)) %>%
column_spec(5, color = “white”,
background = spec_color(mtcars$drat[1:6], end = 0.7),
popover = paste(“am:”, mtcars$am[1:6]))
4. dt (License: GPL-3)
dt is an abbreviation of ‘DataTables.’ Data objects in R can be rendered as HTML tables using the JavaScript library ‘DataTables’ (typically via R Markdown or Shiny). You can find more about dt here.
For installing the dt package from CRAN, use the following command:
install.packages(‘DT’)
For installing the development version of dt from GitHub, use the following command:
remotes::install_github(‘rstudio/DT’)
Next, we will import the dt library package.
library(DT)
The DT package’s main feature is its ability to provide filtering, pagination, and sorting to HTML tables. By using this package, we can slice, scroll through, and arrange tables to understand the table contents better.
datatable(
data = mtcars,
caption = “Table”,
filter = “top”
)
5. flextable (License: GPL-3)
flextable package helps you to create reporting table from a dataframe easily. You can merge cells, add headers, add footers, change formatting, and set how data in cells is displayed. Table content can also contain mixed types of text and image content. Tables can be embedded from R Markdown documents into HTML, PDF, Word, and PowerPoint documents and can be embedded using Package Officer for Microsoft Word or PowerPoint documents. Tables can also be exported as R plots or graphic files, e.g., png, pdf, and jpeg. You can find more about flextable here.
For installing the flextable package from CRAN, use the following command:
install.packages(“flextable”)
For installing the development version of flextable from GitHub, use the following command:
devtools::install_github(“davidgohel/flextable”)
Next, we will import the flextable library package.
library(flextable)
For this library, the main function is flextable. We will call the flextable
function to view the basic version of the table as shown below:
flextable(df)
We will use the set_flextable_defaults
function to change the default appearance of the table.
set_flextable_defaults(
font.family = “Arial”, font.size = 10,
border.color = “#e5383b”,
padding = 6,
background.color = “#EFEFEF”)
flextable(head(df)) %>%
bold(part = “header”)
6. reactable (License: MIT + file LICENSE)
reactable()
creates a data table from tabular data with sorting and pagination by default. The data table is an HTML widget that can be used in R Markdown documents and Shiny applications or viewed from an R console. It is based on the React Table library and made with reactR. There are many features of reactable; some of them are given below:
- It creates a data table with sorting, filtering, and pagination
- It has built-in column formatting
- It supports custom rendering via R or JavaScript
- It works seamlessly within R Markdown documents and the Shiny app
For installing the reactable package from CRAN, use the following command:
install.packages(“reactable”)
For installing the development version of reactable from GitHub, use the following commands:
# install.packages(“devtools”)
devtools::install_github(“glin/reactable”)
Next, we will import the reactable library package.
library(reactable)
We will use the reactable()
function to create a data table. The table will be sortable and paginated by default:
reactable(mtcars)
To change the table’s default appearance, we will use the reactableTheme()
function. The global reactable.theme option can also be used if you want to set the default theme for all tables.
library(reactable)
reactable(mtcars)
options(reactable.theme = reactableTheme(
color = “black”,
backgroundColor = “#bde0fe”,
borderColor = “#a3b18a”,
stripedColor = “#a3b18a”,
highlightColor = “#2b2d42”
))
7. reactablefmtr (License: MIT + file LICENSE)
The reactablefmtr package improves the appearance and formatting of tables created using the reactable R library. The reactablefmtr package includes many conditional formatters that are highly customizable and easy to use.
For installing the reactablefmtr package from CRAN, use the following command:
install.packages(“reactablefmtr”)
For installing the development version of reactablefmtr from GitHub, use the following commands:
remotes::install_github(“kcuilla/reactablefmtr”)
The reactable package in R allows you to create interactive data tables. However, formatting tables inside reactable requires a large amount of code, which might be challenging for many R users and needs to be more scalable. The data_bars()
function in the reactablefmtr library makes it much easier to create bar charts.
library(reactablefmtr)
reactable(data,defaultColDef = colDef(
cell = data_bars(data,text_position = “outside-base”)
))
There are several ways to alter the appearance of data_bars()
, including bar alignment, text label location, and the ability to add icons and images to the bars.
library(reactablefmtr)
reactable(data,defaultColDef = colDef(cell = data_bars(df, box_shadow = TRUE, round_edges = TRUE,
text_position = “outside-base”,
fill_color = c(“#e81cff”, “#40c9ff”),
background = “#e5e5e5”,fill_gradient = TRUE)
))
Conclusion
In this article, we discussed seven powerful R packages to create beautiful tables for a given dataset. There are many more R libraries, and indeed some new ones will also be developed in the future. But this tutorial can be helpful to get started with these packages for anyone looking to create more beautiful and effective tables in R.