r markdown preserve xlink in svg

I'm trying to knit a rmd to html that includes an svg file and preserves its clickable link (xlink / <a> ref), but it seems that knitr converts or embeds the svg as an <img>, losing or inactivating the link. I've tried loading the svg three ways:

  • copying the svg code directly
  • using markdown image loading syntax
  • using knitr::include_graphics

None work as intended. Preferred method would be 2 or 3 (loading a svg file).

Here's a minimal rmd example:

---
title: "Untitled"
output: html_document
---

# directly embed svg tag does not properly display the circle

<svg viewBox="0 0 100 100" xmlns="http://www.w3.org/2000/svg">
  <!-- A link around a shape -->
  <a href="https://developer.mozilla.org/en-US/docs/Web/SVG/Element/a">
    <circle cx="50" cy="40" r="35"/>
  </a>

  <!-- A link around a text -->
  <a href="https://developer.mozilla.org/en-US/docs/Web/SVG/Element/a">
    <text x="50" y="90" text-anchor="middle">
      &lt;circle&gt;
    </text>
  </a>
</svg>


# Use markdown to load SVG places svg inside <img>

![](testsvglink.svg)

# use r knitr::include_graphics places svg inside <img>

```{r}
knitr::include_graphics("testsvglink.svg")
```

And the file testsvglink.svg:

<svg viewBox="0 0 100 100" xmlns="http://www.w3.org/2000/svg">
  <!-- A link around a shape -->
  <a href="https://developer.mozilla.org/en-US/docs/Web/SVG/Element/a">
    <circle cx="50" cy="40" r="35"/>
  </a>

  <!-- A link around a text -->
  <a href="https://developer.mozilla.org/en-US/docs/Web/SVG/Element/a">
    <text x="50" y="90" text-anchor="middle">
      &lt;circle&gt;
    </text>
  </a>
</svg>

Solution 1:

You could include your svg file using htmltools::includeHTML:

---
output: html_document
---

```{r}
htmltools::includeHTML("testsvglink.svg")
```

enter image description here