适用于R的Huxtable包:如何在书本中正确引用huxtables?

时间:2018-10-18 06:47:40

标签: r

用书本编译报告在引用由huxtable软件包生成的表时,我遇到了困难。对于我的工作,需要创建LaTex / PDF以及报告的HTML版本。

渲染文档时,knitr :: is_XXX_output()选择显示表格的最佳方式,请参见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
}
```

我不确定是否建议使用huxtable提供的标题和标签命令

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

或针织

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

对于数字,后者工作得很好,但不幸的是,对于表格而言,效果不是很好。

下面讨论的“ tab.cap”钩子不能与bookdown一起使用,并且是否需要PDF和HTML。 Using table caption on R markdown file using knitr to use in pandoc to convert to pdf

非常感谢您的帮助和建议!

1 个答案:

答案 0 :(得分:0)

如果您升级到huxtable 4.3.0(现在在CRAN上),它将自动为您处理书本表标题。这是一个简短的示例:

---
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")

```

并非所有事物都是完美的。如果设置了echo = TRUE,则需要在TeX标头中的\usepackage[table]{xcolor}之前手动插入\usepackage{fancyvry}