rlistpdf

Exporting a list of dataframes to a pdf with multiple pages in R


I'm attempting to create a report in PDF format based on a list with multiple dataframes. Ideally, each dataframe would become a table, which is then printed on its own page. Accomplishing this in excel is no problem, but when I try to write the list to a PDF, I get an single page output with the results of each dataframe squished or stacked on top of each other (see this image: [1]: https://i.sstatic.net/2JExKUM6.png). When I run the pdf generation code, this is the console output:

> pdf(file= "troubleshoot.pdf", width = 10, height = 6, onefile = TRUE )
> grid.table(output)
> dev.off()
null device 
          1 

Minimal reproducible dataset:

    structure(list(`Person ID` = c(256, 257, 258, 259, 260, 261, 
262, 266, 267, 268), Gender = c("Female", "Female", "Male", "Undisclosed", 
"Male", "Male", "Male", "Male", "Male", "Male"), Race = c("Asian", 
"White", "White", "Black or African American", "Undisclosed", 
"Black or African American", "Undisclosed", "Undisclosed", "Undisclosed", 
"Undisclosed")), row.names = c(NA, -10L), class = c("tbl_df", 
"tbl", "data.frame"))

Minimal reproducible code:

library(tidyverse)
library(readxl)
library(writexl)
library(openxlsx)
library(zoo)
library(grid)
library(gridextra)

output<-list() 

output[["uniquepeople"]]<-people%>% 
  select(`Person ID`)%>%
  summarize(`Number Of People`=n())

output[["gender"]]<-people%>% 
  select(`Gender`)%>%
  table()%>%
  as.data.frame()%>%
  rename(`Count of People`=`Freq`)
 
output[["race"]]<-people%>% 
  select(`Race`)%>%
  table()%>%
  as.data.frame()%>%
  rename(`Count of People`=`Freq`)


##### Output----

write.xlsx(output,"troubleshoot.xlsx", colWidths= "auto") 

pdf(file= "troubleshoot.pdf", width = 10, height = 6, onefile = TRUE )
grid.table(output)
dev.off()

I will note that I cannot use LaTeX to help - it's not installed on my machine and I can't install it without permission from my IT department (more trouble than it's worth to ask). My machine also pitches a fit sometimes with PanDoc (something about OneDrive and Sharepoint does not like it).

Any insight is appreciated! Thanks!


Solution

  • what about:

    ## example list of dataframes:
    output <- list(flowers = iris, cars = mtcars)
    
    library(grid)
    library(gridExtra)
    
    pdf('test.pdf')
    
    lapply(output, FUN = \(d){
      grid.table(d)
      grid.newpage()
    })
    
    dev.off()
    

    Anyhow, you might want to give install.packages("tinytex") a try.