How to add a hyperlink to an image created by `knitr::include_graphics()`

Based on my understanding of the R markdown syntax, this is how I add a hyperlink to an embedded image in an R markdown document.


But for some reason, I want to embed an external image not using the above syntax, but using the knitr::include_graphics() function inside the R code chunk, and I want to add a hyperlink to it. So far I couldn't figure out how to do it. For example, how can I create a hyperlink to from the figure created by this code chunk?


I don't think there is a built-in way to do this in RMarkdown. However, you can use the htmltools package to build commands that can be put directly into your knitted document (assuming you're using HTML as an output).

This function will build the code to create a link (using the <a> tag or a() function) wrapped around an image (using the <img> tag or img() function). RMarkdown renders these as expected.

image_link <- function(image,url,...){

It also allows you to specify things such as the width or height of the image. Calling image_link(image_file,url,width="30px") will set the width to be 30 pixels, and I believe the height will be scaled by default to maintain the aspect ratio. Any other named arguments passed to this function will be used in the <img> tag when the html code is built.

1 Like

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

If you have a query related to it or one of the replies, start a new topic and refer back with a link.