如何使用 huxtable 创建 table 以使用 knitr 生成 LATEX pdf 输出?

How do I create a table using huxtable to produce a LATEX pdf output with knitr?

我正在尝试使用 huxtable 包生成 table,但我遗漏了一些东西:

首先我尝试了下面的代码(这是git中的例子):

<<test>>=
color_demo <- matrix('text', 7, 2)
rainbow <- c('red', 'orange', 'yellow', 'green', 'blue', 'turquoise', 'violet')
color_demo <- as_hux(color_demo)                  %>% 
    set_text_color(rainbow)                     %>% # text rainbow goes down columns
    set_background_color(rainbow, byrow = TRUE) %>% # background color rainbow goes along rows
    set_all_borders(1)                          %>% 
    set_all_border_colors('white')               %>%
    print_latex()
@

产生以下输出,table 内容用双 ## 字符转义。

我也尝试过使用 asis 块选项,但后来我获得了以下内容,因此测试可能并不意味着 运行 使用此选项:

这是我的可重现代码:

\documentclass[a4paper]{article}

\title{test for huxtable}

\begin{document}
\maketitle
<<load_libraries, echo = FALSE, eval = TRUE, results ="hide">>=
library(knitr) 
library(huxtable)
@
<<test>>=
color_demo <- matrix('text', 7, 2)
rainbow <- c('red', 'orange', 'yellow', 'green', 'blue', 'turquoise', 'violet')
color_demo <- as_hux(color_demo)                  %>% 
    set_text_color(rainbow)                     %>% # text rainbow goes down columns
    set_background_color(rainbow, byrow = TRUE) %>% # background color rainbow goes along rows
    set_all_borders(1)                          %>% 
    set_all_border_colors('white')               %>%
    print_latex()
@
<<test2,results ="asis">>=
color_demo <- matrix('text', 7, 2)
rainbow <- c('red', 'orange', 'yellow', 'green', 'blue', 'turquoise', 'violet')
color_demo <- as_hux(color_demo)                  %>% 
    set_text_color(rainbow)                     %>% # text rainbow goes down columns
    set_background_color(rainbow, byrow = TRUE) %>% # background color rainbow goes along rows
    set_all_borders(1)                          %>% 
    set_all_border_colors('white')               %>%
    print_latex()
@

\end{document}

如果您 运行 huxtable 函数 report_latex_dependencies,您应该会发现这组包需要包含在您的序言中。

\usepackage{array}   
\usepackage{caption}
\usepackage{graphicx}
\usepackage{siunitx}
\usepackage[table]{xcolor}
\usepackage{multirow}
\usepackage{hhline}
\usepackage{calc}
\usepackage{tabularx}

当我包含它们时,您的代码生成了您想要的彩色框。