简体   繁体   English

可在 R markdown `asis` 块中反应,不显示循环

[英]reactable in R markdown `asis` chunk with loop not displayed

I want to create dynamic sections in my R markdown document.我想在我的 R markdown 文档中创建动态部分。 For this, I use R chunks with the asis output type.为此,我使用 R 块和asis output 类型。 The chunks contain tables created by the reactable package.这些块包含由可反应的reactable创建的表。

I cannot get the tables to print when I create them in a for-loop.当我在 for 循环中创建表格时,我无法打印它们。 I know that one usually must wrap plots or the like within print() in loops, but that had no effect in my case.我知道通常必须在print()中循环包装绘图等,但这对我的情况没有影响。

How can I get the tables to print?如何让表格打印?

---
title: "Test"
author: "Test"
date: "29 11 2021"
output: html_document
---

```{r include=FALSE}
library(reactable)

```

```{r results='asis', echo=FALSE}

cat("\n\n## My header 1 \n\n")

reactable(data.frame(test = rnorm(3)))  ## This works

```



```{r results='asis', echo=FALSE}



for (i in 1:3) {
  
  cat("\n\n## My header ", i+1, "\n\n")
  
  print(reactable(data.frame(test = rnorm(3))))  ## shows nothing
  
}

```

I just found out, that reactable uses htmlwidgets under the hood.我刚刚发现, reactable在引擎盖下使用了htmlwidgets So one can wrap the result in shiny::tagList() to display it in a loop.因此,可以将结果包装在shiny::tagList()中以循环显示。

---
title: "Test"
author: "Test"
date: "29 11 2021"
output: html_document
---

```{r include=FALSE}
library(reactable)

```

```{r results='asis', echo=FALSE}

cat("\n\n## My header 1 \n\n")

reactable(data.frame(test = rnorm(3)))  ## This works

```



```{r results='asis', echo=FALSE}


for (i in 1:3) {
  
  cat("\n\n## My header ", i+1, "\n\n")
  
  print(shiny::tagList(reactable(data.frame(test = rnorm(3)))))  ## now it works
  
}

```

You could try to export your react-tables as temporary html-files that you then import as text and delete afterwards.您可以尝试将您的反应表导出为临时 html 文件,然后将其作为文本导入并在之后删除。

Here is a solution that worked for me:这是一个对我有用的解决方案:

---
title: "Test"
author: "Test"
date: "29 11 2021"
output: html_document
---

```{r include=FALSE}
library(reactable)

```

```{r results='asis', echo=FALSE}

cat("\n\n## My header 1 \n\n")

reactable(data.frame(test = rnorm(3)))  ## This works

```




```{r results='asis', echo=FALSE}



for (i in 1:3) {

  cat("\n\n## My header ", i+1, "\n\n")

  htmlwidgets::saveWidget(reactable(data.frame(test = rnorm(3))),
                          file = 'temp.html')
  cat(readr::read_lines('temp.html')[-1])
  file.remove('temp.html')
}

```

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM