Diego López
Diego López

Reputation: 43

How to make a link in R Markdown output to get a pdf or HTML with hyperlinks in text

I have a data frame output in R Markdown. My problem is that the links column is very long and I would like to make hyperlinks in the column of text ("model" in this case) with the "link" column. In R Markdown it is possible to make a link in plain text but I don't know how to make it in a data output. I want to get a pdf or HTML file.

library (dplyr)
library (data.table)

data <- select(mtcars[1:4,], cyl, gear)
data <- setDT(data, keep.rownames = TRUE)
colnames(data) <-c("model","cyl","gear")
data$link <- paste('http://example.com/',data$model, sep = "")

data
            model cyl gear                              link
1:      Mazda RX4   6    4      http://example.com/Mazda RX4
2:  Mazda RX4 Wag   6    4  http://example.com/Mazda RX4 Wag
3:     Datsun 710   4    4     http://example.com/Datsun 710
4: Hornet 4 Drive   6    3 http://example.com/Hornet 4 Drive

I would like to get the model column with hyperlinks:

model                                      cyl    gear                             
[Mazda RX4](http://example.com/Mazda)        6       4      
[Mazda RX4 Wag](http://example.com/Mazda)    6       4  
[Datsun 710](http://example.com/Datsun)      4       4     
[Hornet 4 Drive](http://example.com/Hornet)  6       3 

But when I do this in R- Markdown I have not results. Is there any way to do it? Thanks in advance.

Upvotes: 4

Views: 1676

Answers (1)

Ryan Morton
Ryan Morton

Reputation: 2695

You'll have to work out your format, but you can have R Markdown print results='asis' in the chunk options:

---
output:
  pdf_document: default
  html_document: default
---

```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = FALSE)
library (dplyr)
library (data.table)

data <- select(mtcars[1:4,], cyl, gear)
data <- setDT(data, keep.rownames = TRUE)
colnames(data) <-c("model","cyl","gear")
data$link <- paste('http://example.com/',data$model, sep = "")
data$markdown_output <- paste0("[", data$model, "](",data$link, ")")
```

## R Markdown Output

```{r output, results='asis'}
data$markdown_output
```

Upvotes: 2

Related Questions