Search code examples
rdataframer-markdownkablekableextra

R - kableExtra create column with link


I am creating a table with a column with hyperlinks, but those hyperlinks are very long and I wanted to substitute the long text for an image, to click it and to open the link in a new tab.

For example, with this code

df = iris[c(1,51,101),]
df$hyperlink = c("https://en.wikipedia.org/wiki/Iris_setosa", "https://en.wikipedia.org/wiki/Iris_versicolor", "https://en.wikipedia.org/wiki/Iris_virginica")

kable(df,format = "html")%>%
  kable_styling(bootstrap_options = c("hover", "condensed"), full_width = F)

I obtain the last column as a hyperlinks, but what I would like is to put an image that, when clicked, it opens the url (preferably in a new window or tab)


Solution

  • You add clickable images by adding the appropriate html tags. <a href='...'></a> is for hyperlinks, and <img src='...'> is for images. Simply place the image tag between the opening and closing html tags. Also, be sure to include escape=FALSE in the kable statement to make it work.

    library(kableExtra)
    library(dplyr)
    df = iris[c(1,51,101),]
    df$hyperlink = c("<a href='https://en.wikipedia.org/wiki/Iris_setosa'><img src='setosa.png' /</a>", 
    "<a href='https://en.wikipedia.org/wiki/Iris_versicolor'><img src='versicolor.png' /></a>", 
    "<a href='https://en.wikipedia.org/wiki/Iris_virginica'><img src='virginica.png' /></a>")
    
    kable(df,escape=FALSE,format = "html")%>%
      kable_styling(bootstrap_options = c("hover", "condensed"), full_width = F)