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

后端 未结 2 750
闹比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:44

    When using results='asis' argument, the renderer (here DT) has to be initialized once before being applied on a asis list.
    This seems to be a general problem, see here with leaflet, and here with Highcharter.

    The answer to this general question has been given here.

    In this case:

    ---
    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')
    # initialize the renderer
    data.frame() %>%
      DT::datatable() %>%
      knitr::knit_print() %>%
      attr('knit_meta') %>%
      knitr::knit_meta_add() %>%
      invisible()
    
    ```
    
    
    ```{r , results='asis'}
    #Remove already printed element and print the rest
    df_list[[1]] <- NULL
    
    map(df_list, ~DT::datatable(.x) %>%
          htmltools::tagList() %>%
          print())
    
    ```
    
    
    0 讨论(0)
  • 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())
    ```
    
    0 讨论(0)
提交回复
热议问题