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)))
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:
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:
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)
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:
# 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")
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With