Links in RMarkdown Datatable

Viewed 201

I'm trying to create active links in an RMarkdown document. In the code below, the basic kable table is perfect, but the datatable version turns the links into text

---
title: "Example"
output: html_document
---

```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
library(knitr)
library(DT)
example.df <- data.frame("link"=c("[Tokyo](https://en.wikipedia.org/wiki/Tokyo)","[Paris](https://en.wikipedia.org/wiki/Paris)"), "country"=c("Japan","France"))


kable(example.df)
datatable(example.df)

2 Answers

There are 2 changes needed to it to work with datatable.

  1. Format the links as raw HTML, not Markdown
  2. Include relevant escape arguments as to NOT escape the link column. For simplicity in this example, we use escape=FALSE

Here is a full reprex answer.

---
title: "Example"
output: html_document
---

```{r setup, include=TRUE}
knitr::opts_chunk$set(echo = TRUE)

library(knitr)
library(DT)
example.df.kable <- data.frame("link"=c("[Tokyo](https://en.wikipedia.org/wiki/Tokyo)","[Paris](https://en.wikipedia.org/wiki/Paris)"), "country"=c("Japan","France"))

example.df.datatable <- data.frame("link"=c(
'<a href="https://en.wikipedia.org/wiki/Tokyo">Tokyo</a>',
'<a href="https://en.wikipedia.org/wiki/Paris">Paris</a>'),
"country"=c("Japan","France"))

kable(example.df.kable)
datatable(example.df.kable)  # This does NOT show the links
datatable(example.df.datatable)  # This does NOT show the links
datatable(example.df.datatable, escape=FALSE)  # This does show the links
Related