I am knitting an Rmd file to docx (required by the client) and have come across a weird issue: if I knit to HTML, internal anchors I've included work (so they can click on "Table 1" and it will take them to it. However, if I knit to .docx, the links appear in text, but the anchors seem to have disappeared. If I knit to .pdf, neither appear.
The links and anchors are generated in a function (tabRef()
)that auto-numbers each table, as well as applies a caption to it.
The following can be copied into an Rmd file to demonstrate what I mean:
---
title: "Pander Test"
author: "Matt"
date: "Wednesday, January 07, 2015"
output:
html_document:
keep_md: yes
pdf_document: default
word_document: default
---
```{r, echo=FALSE, message=FALSE}
require(pander)
tabRef <- local({
tag <- numeric()
created <- logical()
used <- logical()
function(label, caption, prefix = options("tabcap.prefix"),
sep = options("tabcap.sep"),
prefix.highlight = options("tabcap.prefix.highlight")) {
i <- which(names(tag) == label)
if (length(i) == 0) {
i <- length(tag) + 1
tag <<- c(tag, i)
names(tag)[length(tag)] <<- label
used <<- c(used, FALSE)
names(used)[length(used)] <<- label
created <<- c(created, FALSE)
names(created)[length(created)] <<- label
}
if (!missing(caption)) {
# Create Anchor
created[label] <<- TRUE
sprintf('<a name="%s"/> %s',
paste0("Table", i),
paste0(prefix.highlight, prefix, i, sep, prefix.highlight, " ", caption))
} else {
# Create Link to Anchor
used[label] <<- TRUE
sprintf('[%s](#%s)',
paste0(prefix, tag[label]),
paste0("Table", tag[label]))
}
}
})
options(tabcap.prefix = "Table I.", tabcap.sep = ".", tabcap.prefix.highlight = "**")
```
Reference the tables:
Here is the first `r tabRef("MLtab")`. You should also see `r tabRef("USAtab")`.
Oh, and this one is also pretty cool: `r tabRef("MLtab2")`.
Make the tables:
```{r, echo=FALSE}
ml <- with(lm(mpg ~ hp + wt), data = mtcars)
set.caption(tabRef("MLtab", "Linear regression with mtcars."))
pander(ml)
```
Add figure for some white space.
```{r}
plot(cars)
```
Here is another:
```{r, echo=FALSE}
pr <- prcomp(USArrests)
set.caption(tabRef("USAtab", "Principal Components Analysis."))
pander(pr)
```
Add figure for some white space.
```{r}
plot(cars)
```
Add figure for some white space.
```{r}
plot(cars)
```
Add figure for some white space.
```{r}
plot(cars)
```
```{r, echo=FALSE}
st <- table(mtcars$am, mtcars$gear)
set.caption(tabRef("MLtab2", "Simple Table."))
pander(st)
```
What about linking backward? Let's try to see `r tabRef("MLtab")`.
Any suggestions would be really appreciated!