问题描述
我经常想将列表中包含的数据帧作为rmarkdown文档中的分页表打印出来.如果选择了正确的df_print
选项,则分别调用每个数据帧将呈现所需的输出.但是,拥有列表的要点是,数据帧的数量取决于传递给rmarkdown文档的参数而有所不同.所以这不是真正的解决方案.
I often want to print out the dataframes contained in a list as paged tables in my rmarkdown documents. Calling each dataframe individually renders the desired ouptut if the right df_print
option is selected. However, the point of having a list is that the number of dataframes varies depending on the parameters passed to the rmarkdown document; so that's no real solution.
基于 Vincent Guyader对这个问题的回答和 rmarkdown::paged_table
的示例,我尝试执行以下操作但未成功.
Based on Vincent Guyader's answer to this question and on this example of rmarkdown::paged_table
, I've tried to do the following without success.
有没有办法实现这一目标?我很乐意使用任何类似于df_print
选项的支持分页的软件包.
Is there a way to achieve this at all? I'd be happy to use any package that supports pagination remotely resembling the df_print
option.
---
title: "Printing paged tables from a list of dataframes in Rmarkdown"
output:
html_document:
df_print: paged
---
```{r}
library(DT)
library(rmarkdown)
library(purrr)
library(knitr)
df_list <- list("cars" = mtcars, "flowers" = iris)
knitr::opts_chunk$set(echo = FALSE, warning = FALSE, message = FALSE, results='asis')
```
### Desired output but impossible to generalise
```{r}
df_list[["cars"]]
```
```{r}
df_list[["flowers"]]
```
### datatable shows as blanks on the page
```{r}
map(df_list, ~DT::datatable(.x) %>%
htmltools::tagList() %>%
print())
```
### rmarkdown outputs dataframe contents as one very long string
```{r}
map(df_list, rmarkdown::paged_table)
```
推荐答案
问题是,呈现Datatable所需的JS依赖项未包含在HTML输出中.我从此处借用的解决方法是添加代码块
The issue is that the JS dependencies needed to render the Datatable are not included in the HTML output. A workaround which I borrowed from here is to add a code chunk
```{r init-step, include=FALSE}
DT::datatable(mtcars)
```
在loop或map语句之外,以确保包括JS依赖项.另外,我建议切换到purrr::walk
,因为使用map
会使表绘制两次.
outside of the loop or map statement which ensures that the JS dependencies are included. Also, I would recommend to switch to purrr::walk
as using map
has the effect that the tables are plotted twice.
---
title: "Printing paged tables from a list of dataframes in Rmarkdown"
output:
html_document:
df_print: paged
---
```{r}
library(DT)
library(rmarkdown)
library(purrr)
library(knitr)
df_list <- list("cars" = mtcars, "flowers" = iris)
knitr::opts_chunk$set(echo = FALSE, warning = FALSE, message = FALSE, results='asis')
```
### Desired output but impossible to generalise
```{r}
df_list[["cars"]]
```
```{r}
df_list[["flowers"]]
```
### datatable shows as blanks on the page
```{r init-step, include=FALSE}
DT::datatable(mtcars)
```
```{r}
walk(df_list, ~DT::datatable(.x) %>%
htmltools::tagList() %>%
print())
```
这篇关于在rmarkdown中将存储在列表中的任何数量的数据帧打印为分页表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!