Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Including links within Rmarkdown tables (pdf)

I am trying to include links to particular webpages in a 'kable' table in Rmarkdown, when creating a pdf.

The table has 4 columns, and I wish for the links to be in the second column, which currently includes strings. The output of the table is given below;

    knitr::kable(ind_rank_table_final,row.names = FALSE,caption = "Industry Rank",align = rep("l",ncol(ind_rank_table)))
like image 829
Robert Honeybul Avatar asked Jan 29 '16 06:01

Robert Honeybul


2 Answers

Using paste0, you can construct markdown-formatted URLs in your dataframe, and then pass that to kable, like so:

---
output: pdf_document
---
```{r}
# some urls
urls <- rep("https://stackoverflow.com/", 10)
# use paste0 to compose markdown-formatted hyperlinks
mtcars$mpg <- paste0("[", mtcars$mpg, "](", urls, ")")
# print the table, with hyperlinked text
knitr::kable(head(mtcars))
```

And you can see the result, blue text in the mpg column, and if I hover my mouse over, I see the URL:

enter image description here

If you want to print the URLs in the table, and have them clickable, then you'de do something like this mtcars$mpg <- paste0("[", urls, "](", urls, ")") like so:

enter image description here

Is that what you're after? This use of paste0 is pretty handy for doing all sorts of things to tables, for example, combining multiple values in one cell, and applying conditional formatting (like bold for significant values)

like image 164
Ben Avatar answered Nov 11 '22 06:11

Ben


For those knitting to PDFs using bookdown, @Ben's answer will not get you fully the way there. As @mavericks pointed out, you will still see the full text ([21](https://stackoverflow.com/), to keep with @maverick's example).

To fix this, add the argument format = "pipe" or format = "simple" to kable(). The "latex" option, while generating a working link, will display like @maverick's example. The default behavior for kable() is to automatically determine the format, which I guess in the case of a bookdown document must be "latex"?

I don't know, but this should generate @Ben's first table for bookdown users:


output: bookdown::pdf_document2

# some urls
urls <- rep("https://stackoverflow.com/", 10)
# use paste0 to compose markdown-formatted hyperlinks
mtcars$mpg <- paste0("[", mtcars$mpg, "](", urls, ")")
# print the table, with hyperlinked text
knitr::kable(head(mtcars), format = "simple")
like image 1
mvanaman Avatar answered Nov 11 '22 07:11

mvanaman