【问题标题】:How to I get tab_model to display properly in Rmarkdown PDF?如何让 tab_model 在 Rmarkdown PDF 中正确显示?
【发布时间】:2025-12-11 18:40:01
【问题描述】:

我意识到这可能很简单,但我已经查看并找不到如何在发送到 PDF 的 Rmarkdown 文档中使用 sjPlot::tab_model 的示例。

这是可重现的代码:

---
title: "test"
author: "Me"
date: "2020/12/6"
output: pdf_document
---

```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
library(sjPlot)

一张桌子

tab_model(lm(mpg~cyl, data=mtcars))

我得到的看起来像这样:

一张桌子 tab_model(lm(mpg~cyl, data=mtcars)) mpg 预测器 估计 CI p (截距) 37.88 33.65 – 42.12

【问题讨论】:

  • 不清楚您的问题是什么。你的输出应该是什么样的?输出当前是否只是一串未在任何表格中格式化的单词?
  • @Dylan_Gomes 没错,输出只是文本,而不是格式化的表格。
  • 刚刚创建了一个函数来创建 sjPlot::tab_model() 的 tex 和 pdf 版本:github.com/gorkang/html2latex

标签: r r-markdown sjplot


【解决方案1】:

这是一个众所周知的问题,包的创建者(Daniel)在这里回复:https://github.com/strengejacke/sjPlot/issues/712

与此同时,我最终创建了几个函数来提供帮助。

请参阅 Github 存储库https://github.com/gorkang/html2latex/

在 repo 中,您可以找到一个带有分步说明的 example.Rmd 文件。它适用于 Ubuntu 20.04 系统。

【讨论】:

    【解决方案2】:

    我尝试将 html 保存在 tab_model 函数中,然后将其读入 Rmd 文档 Include HTML files in R Markdown file?

    ```{r setup, include=FALSE}
    knitr::opts_chunk$set(echo = TRUE)
    library(sjPlot)
    ```
    
    ```{r plot}
    
    tab_model(lm(mpg~cyl, data=mtcars),file="test.html")
    
    ```
    
    
    ```{r, echo=FALSE}
    htmltools::includeHTML("test.html")
    ```
    

    但是我遇到了同样的问题,这让我觉得在 Rmd 中有一些格式化 html 表格的选项,但我似乎找不到解决方案。

    这里有一个相关的帖子:https://*.com/a/33182503/9096420,但是 tab_model 不能很好地与那里的代码一起工作,因为它需要一个数据框。

    我认为有一些技巧可行,但并不理想。您可以将输出保存为 png,然后将其包含在 Rmd 文档中https://*.com/a/25167279/9096420

    ---
    title: "Untitled"
    author: "Dylan Gomes"
    date: "12/7/2020"
    output: pdf_document
    ---
    ![Caption for the picture.](test.png) ## this file 'test.png' needs to be in the working directory.
    

    【讨论】: