Reputation: 2669
I am using the table1::table1()
function to make the table I want in my paper but I can't see how to reference the table throughout the paper. Is there a way to reference a table made with table1() using syntax like: \@ref(tab:x)
in R Markdown?
Upvotes: 0
Views: 1210
Reputation: 44788
This is possible, but it's a bit tricky.
The issue is that the table1
package doesn't support labels in the form that Pandoc is looking for, so you need to put them in by hand.
However, table1
marks its output in a way that tells Pandoc to ignore the additions you have to make. So you have to do two workarounds in the following:
caption
argument to table1()
.(\\#tab:thetablename)
, where you replace thetablename
with a
unique string of your own choice.table1()
function in knitr::asis_output()
.Using one of the examples from the ?table1
help page,
```{r echo=FALSE}
library(table1)
dat <- expand.grid(id=1:10, sex=c("Male", "Female"), treat=c("Treated", "Placebo"))
dat$age <- runif(nrow(dat), 10, 50)
dat$age[3] <- NA # Add a missing value
dat$wt <- exp(rnorm(nrow(dat), log(70), 0.2))
label(dat$sex) <- "Sex"
label(dat$age) <- "Age"
label(dat$treat) <- "Treatment Group"
label(dat$wt) <- "Weight"
units(dat$age) <- "years"
units(dat$wt) <- "kg"
knitr::asis_output(table1(~ sex + age + wt | treat, data=dat,
caption = "(\\#tab:thetab)The caption"))
```
where the last statement contains both modifications. This produces
output (using bookdown::html_document2
format) that looks like this:
and I could refer to the table by number using \@ref(tab:thetab)
in other parts of the text.
Upvotes: 2