【问题标题】:Rmarkdown HTML rendering issueRmarkdown HTML 渲染问题
【发布时间】:2022-01-01 10:20:54
【问题描述】:

我正在尝试打印 HTML 表格列表,但由于某种原因,当我编织文档时,我得到了用于输出的原始 HTML 代码,而不是渲染的表格。示例:

---
title: "html-render-issue"
output: html_document
---
library(tidyverse)
library(gtsummary)

# this table renders correctly:
tbl_summary(iris)

# but this table does not!!
tables <- list(tbl_summary(iris), tbl_summary(cars))
print(tables)

我不明白为什么会这样,我尝试使用 for 循环索引到列表中

for (i in 1:2) {
  print(tables[[i]])
}

但这似乎也不起作用!没有做tables[[1]]; tables[[2]] 等(确实有效),有没有办法遍历列表并获得我想要的输出?

【问题讨论】:

    标签: html r r-markdown knitr gtsummary


    【解决方案1】:

    考虑在r 块中使用results = "asis",然后使用knitr::knit_print 代替print

    ```{r, results = "asis", echo = FALSE}
     library(gtsummary)
    
     # this table renders correctly:
     tbl_summary(iris)
    
     # but this table does not!!
     tables <- list(tbl_summary(iris), tbl_summary(cars))
     for (i in 1:2) {
       cat(knitr::knit_print(tables[[i]]))
     }
    ```
    

    -输出

    【讨论】:

    • 感谢阿克伦!你知道我最初尝试的问题是什么吗?我认为这与将参数视为输出而不是原始 html 的 print() 有关。但是,如果我尝试执行 for (i in 1:2) tables[[i]],我将在针织输出中一无所获!
    • @HankLin 根据?knit_print -the chunk option render is a function that defaults to knit_print().
    【解决方案2】:

    尝试在列表中添加%&gt;% as_gt()

    ---
    title: "html-render-issue"
    output: html_document
    ---
    
    ```{r loop_print, results = 'asis'}
    library(tidyverse)
    library(gtsummary)
    
    tables <- list(tbl_summary(iris), tbl_summary(cars) %>%  as_gt())
    walk(tables, print)               # walk from purrr package to avoid [[1]] [[2]]
    ```
    

    【讨论】:

    • 正是我想要的,谢谢!
    猜你喜欢
    • 2014-07-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-06-07
    • 2022-07-27
    • 2012-08-31
    • 2017-09-17
    相关资源
    最近更新 更多