Printing any number of dataframes stored in list as paged tables in rmarkdown

后端 未结 2 847
闹比i
闹比i 2021-01-23 10:11

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 rig

2条回答
  •  悲&欢浪女
    2021-01-23 10:54

    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)
    ```
    

    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())
    ```
    

提交回复
热议问题