Images and links in a kable table with kableExtra



This post explains how to customize colors in a kable output with the kableExtra package. We’ll go through several examples with reproducible R code the with kableExtra.

Table Data to Viz

Packages


For this post, we need to load the following library:

library(kableExtra)


Dataset


We create a simple dataset with Nobel Prizes (2020). We use 3 columns: name, field and image.

df = data.frame(name = c("E. Charpentier","R. Penrose", "L. Glück", "M. Houghton"),
                field = c("Chemistry", "Physics", "Litterature", "Medicine"),
                image = "" # keep it empty
                )

Add images


The kableExtra relies on the kable package and allows the use of the %>% (pipe) symbole. The main function is named kbl() and is similar to kable().

In order to add images in column, we need to use the column_spec() function with the image argument. Also, to change dimensions of images, we use the spec_image() function into the image arg.

# we use images from the internet, but it works exactly the same
# for images locally stored on your computer!
path_images = c("https://www.nobelprize.org/images/charpentier-111763-landscape-mini-2x.jpg",
                "https://www.nobelprize.org/images/penrose-111758-landscape-mini-2x.jpg",
                "https://www.nobelprize.org/images/gluck-111767-landscape-mini-2x.jpg",
                "https://www.nobelprize.org/images/houghton-111770-landscape-mini-2x.jpg")

df %>%
  kbl(booktabs = T, align = "c") %>%
  kable_styling() %>%
  kable_paper(full_width = T) %>%
  column_spec(3, image = spec_image(path_images, 280, 200) # dimensions of the images
              )
name field image
E. Charpentier Chemistry
R. Penrose Physics
L. Glück Litterature
M. Houghton Medicine

Conclusion

This post explained how to add images and links in a table using the kableExtra library. For more of this package, see the dedicated section or the table section.

Related chart types


Line plot
Area
Stacked area
Streamchart
Time Series



Contact

This document is a work by Yan Holtz. Any feedback is highly encouraged. You can fill an issue on Github, drop me a message on Twitter, or send an email pasting yan.holtz.data with gmail.com.