这不是一个理想的解决方案,但是,使用webshot
包,很容易将 html 文件转换为图像文件,然后可以轻松地将其导入到 R Markdown 中knitr::include_graphics
。这种方法的三个优点是(1)它自动工作; (2) 格式保存良好; (3) 它可以与其他制表包或任何外部 html 文件(或网页)一起使用。此外,我在顶部添加了一些代码,以便 Rmd 自动合并正确的外部文件(.tex 或 .html),具体取决于我编织为 pdf 还是 word。
请注意,如果您还没有使用过webshot
之前,需要运行webshot::install_phantomjs()
(我感谢 JacobG 指出了这一点)。
```{r create_output_logicals, include = FALSE}
# https://stackoverflow.com/questions/62389948/knitris-word-output-to-check-if-the-current-output-type-is-word-just-like
is_word_output <- function(fmt = knitr:::pandoc_to()) {
length(fmt) == 1 && fmt == "docx"
}
# create logical variables that indicate knitting output format
latex_lgl <- knitr::is_latex_output()
html_lgl <- knitr::is_html_output()
word_lgl <- is_word_output()
```
```{r load_packages, include = FALSE}
library(stargazer)
library(webshot)
```
```{r create_table, include = FALSE}
lm1 <- lm(mpg ~ wt, data = mtcars)
lm2 <- lm(mpg ~ wt + cyl, data = mtcars)
stargazer(
lm1, lm2,
type = 'html',
header = FALSE,
out = 'regression_table.html'
)
stargazer(
lm1, lm2,
type = 'latex',
header = FALSE,
out = 'regression_table.tex'
)
```
```{r regression_table_word, echo = FALSE, eval = word_lgl}
webshot(
url = "regression_table.html",
file = "regression_table.png",
zoom = 2 # doubles the resolution
)
knitr::include_graphics("regression_table.png")
```
```{r regression_tables_tex, results = 'asis', echo = FALSE, eval = latex_lgl}
# if not knit to word document, use latex \input for tex tables
# line spacing assumes YAML/header includes: \usepackage{setspace}
# header-includes: |
# \usepackage{setspace}\doublespacing
cat(
'\\singlespacing
\\input{"regression_table.tex"}
\\doublespacing'
)
```
请注意,表格/图像不会在 Word 中居中。由 webshot 创建的图像用空格填充。如果居中很重要,您需要使用以下任一方法修剪图像cliprect
选项中webshot()
或使用类似的东西magick
封装有magick::image_trim
。此外,您可能需要创建 Word 模板 https://stackoverflow.com/questions/49657662/how-can-i-center-image-in-r-markdown-in-knit-word.