How do I include html code within R markdown tables?

#1

So I have the following R chunk in a rmarkdown file:

library(tidyverse)

tibble(" " = '<img src= "img/logos/bos.png" alt="Boston Celtics">', Team = "Boston Celtics", Wins = 82)

I want to display it as a table, which I can do with gt::gt() or kableExtra::kable(), I have no real preference. Obviously, the first column will be printed as text rather than html code.

Is there an easy way to have it evaluated as html code?

0 Likes

#2

Did you tried

tab <- tibble::tibble(" " = '<img src= "img/logos/bos.png" alt="Boston Celtics">', Team = "Boston Celtics", Wins = 82)
knitr::kable(tab)

I don't have you image to try, but on a small example with one of mine, it is working.

The html code is kept as is in kable output.

0 Likes

#3

Thank you! That's it. And I'm embarrassed that it's this simple.

0 Likes

#4

Don't be ! This is always a good idea to look for advices!


If your question's been answered, would you mind marking as solution? It helps other people see which questions still need help, or find solutions if they have similar problems. Here’s how to do it:

0 Likes

#5

It seems if I just use knitr::kable() without specifying the format (which will, I guess, render a markdown table), the images will be displayed, however if I wanted to do knitr::kable(format = "html") to use the functions of kableExtra, the images column will, again, just show the code.

Is there a way to get both working together?

0 Likes

#6

If you want to produce html table code to use with knitrExtra afterwards, you need to take care of escaping.

By default, knitr::kable() will escape special character so that they print correctly in the HTML table. In your case, you don't want that, because you put in your table some html code directly, so you want it as is.

There is an option for that:

knitr::kable(tab, format = "html", escape = FALSE)

With this, no escaping will happen. See the doc for details.

The < and > of your html code for image won't be escape anymore and this should work.

0 Likes

closed #7

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.

0 Likes