简体   繁体   中英

Huxtable package for R: How to correctly reference huxtables in bookdown?

Compiling a report with bookdown I encounter difficulties in referencing tables generated with the huxtable package. For my work, LaTex/PDF, as well as an HTML version of the report, need to be created.

When rendering the document knitr::is_XXX_output() selects the optimal way to display the tables, see MWE:

```{r chunk-label, results='asis', fig.cap='chunk-caption'}
set.seed(1234)
dat <- data.frame(cond = factor(rep(c("A","B"), each=2)), 
                   rating = c(rnorm(2),rnorm(2, mean=.8)))

hux <- as_hux(dat)                    %>%
  set_caption('hux caption')          %>% 
  set_label("tab:hux-label")                                              

if (knitr::is_html_output()) {
  print_html(hux)   # output table html friendly (requires in chunk options "results='asis'")
}
if (knitr::is_latex_output()) {
  hux
}
```

I am not sure whether it is recommended to use the caption and label commands provided by huxtable

  set_caption('pipe caption') and set_label("tab:hux-label")    

or knitr

  chunk-label and fig.cap='chunk caption'

For figures, the latter works very well, but unfortunately not for tables.

The hook for "tab.cap" as discussed in following did not work well with bookdown and if PDF & HTML are needed. Using table caption on R markdown file using knitr to use in pandoc to convert to pdf

Help and recommendations are very much appreciated!

If you upgrade to huxtable 4.3.0 (now on CRAN), it automatically takes care of bookdown table captions for you. Here's a short example:

---
title: "Bookdown test"
output:
  bookdown::pdf_book: default
link-citations: yes
---

```{r setup, include=FALSE}

library(dplyr)
library(huxtable)
knitr::opts_chunk$set(echo = FALSE)

```

My table is \@ref(tab:foo1). The other table is \@ref(tab:foo2). The third is \@ref(tab:foo3).

```{r}


hux(a = 1:5, b = 1:5) %>% 
  set_caption("My labelled table") %>% 
  set_label("tab:foo1")

hux(a = 1:5, b = 1:5) %>% 
  set_caption("My unlabelled table")

hux(a = 1:5, b = 1:5) %>% 
  set_caption("My labelled table, prefix should be autoadded!") %>% 
  set_label("foo2")

hux(a = "A table with no caption, but a label") %>% 
  set_label("tab:foo3")

hux(a = "A table with no caption or label")

```

Not everything is perfect. If you set echo = TRUE you will need to manually insert \\usepackage[table]{xcolor} before \\usepackage{fancyvry} in the TeX header.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM