Images as column headers in R

2020-03-01

Have you ever wanted to include an image as a column header in a data frame? Of course you have!

All joking aside, this is actually surprisingly common in corporate environments, where tables may have the company logo in the header, probably as the first ‘column’. You can actually do this in Rmarkdown, with a little help from rlang, tibble knitr and pander. Here’s how.

I’m going to use Google’s logo cos I’m sure they wouldn’t mind. You need to download a copy of this and you'll need to size it to fit your table. The image below is 115x40 (width x height).

First, load libraries and read in the image with pander, assuming it's in your working directory:

library(pander)
library(knitr)
library(rlang)
library(tibble)
library(magrittr) # fo' da pipe

img <- "google_logo.png" %>% pander::pandoc.image.return()

You’ll notice this is just markdown: img is "![](google_logo.png)". Ok, rlang, pander and knitr magic coming up 🧙‍♀️. The code we’ll use is the following:

tibble(
  {{ img }} := c("Metric One", "Metric Two"),
  `Segment One` = c(100, 250),
  `Segment Two` = c(20, 12)
  ) %>%
  pandoc.table(
    justify = c("left", "right", "right"),
    keep.line.breaks = TRUE
  )

Where {{ img }} uses curly-curly and the walrus operator to access the image variable we’ve created. It gets rendered as markdown thanks to pander’s pandoc.table() and knitr helps with code chunk options. Importantly, these need to include results = 'asis'. So it’ll look like this, minus the #:

#```{r results='asis'}
# amazing code...
#```

So, putting all this together, we get:

tibble(
  {{ img }} := c("Metric One", "Metric Two"),
  `Segment One` = c(100, 250),
  `Segment Two` = c(20, 12),
  `Total for Segments` = c(120, 262)
  ) %>%
  pandoc.table(
    justify = c("left", "right", "right", "right"),
    keep.line.breaks = TRUE
  )

google logo Segment One Segment Two Total for Segments
Metric One 100 20 120
Metric Two 250 12 262

Now that’s a nice table 😍. And so easy! Keep in mind the styling here is basic, but knitting this in RStudio gives me:

rstudiogoogletable

Now that's a nice table.



You're not limited to tables by the way. Have a look at my Stack Overflow answer here that shows how easy it is to use images in the table cells. Long story short:

so table