Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I include hyperlinks in a table within an Sweave document?

I have a data frame containing hyperlinks that I would like to present as clickable links using Sweave. I know about xtable, but am not sure how to use it to treat the contents of a data frame as LaTeX commands.

like image 475
David Lovell Avatar asked Jun 10 '14 03:06

David Lovell


People also ask

Which package is used to insert hyperlinks?

The package hyperref provides LaTeX the ability to create hyperlinks within the document.

How do I add the Hyperref package to the preamble?

You can include this package in your document preamble by using command \usepackage{hyperref}. The package enables you to add links into your document along with a custom description.


1 Answers

One strategy is to use the sanitize.text.function from the print function in xtable. Setting sanitize.text.function = function(x){x} causes print simply to echo the contents of the data frame for later interpretation by LaTeX:

\documentclass{article}

\usepackage{hyperref}

\begin{document}
\title{Example of how to include hyperlinks in Sweave with \texttt{xtable}}
\author{David R. Lovell}
\maketitle

<<load-packages, include=FALSE>>=
require(xtable)
@

<<read-data, tidy=FALSE>>=
hits <- read.table(textConnection(
"Count,Link,Title
1031,http://australianbioinformatics.net/jobs,Jobs
796,http://australianbioinformatics.net/,Home"),
stringsAsFactors=FALSE, sep=",", header=TRUE)
@

<<print-xtable, echo = FALSE, results = 'asis'>>=
print(
  xtable(
    hits,
    align="rrll",
    caption="Top content on \\href{http://australianbioinformatics.net}{AustralianBioinformatics.net} in May 2014."
    ), 
  include.rownames=FALSE
  )
@

<<print-xtable-href, echo = FALSE, results = 'asis'>>=
linkedHits <- transform(hits, href=paste("\\href{", Link, "}{", Title, "}", sep=""))
print(
  xtable(
    subset(linkedHits, select=c(Count, href)),
    align="rrl",
    caption="Top content on \\href{http://australianbioinformatics.net}{AustralianBioinformatics.net} in May 2014, 
    now with added hyperlinks."
    ), 
  include.rownames=FALSE,
  sanitize.text.function = function(x){x}
  )

@

\end{document}

...which produces this PDF output: enter image description here

like image 89
David Lovell Avatar answered Sep 24 '22 07:09

David Lovell