0

I'm a fairly new coder and would appreciate some help.

I'm trying to create a report in Rmarkdown that includes tables with a lot of rows and which will therefore need to appear on multiple pages. I first tried to do this using the gt() command since this is what I use to make smaller tables, but I don't know how to use this command to give repeat headers for each table. My only solution for using the gt() command would be filtering and then copy/paste, but I'm trying to avoid this. I have some legacy code from a different report that achieves a similar goal using the kable() command. I've managed to create the tables I need covering multiple pages with repeating headers. However, I want to be able to create row groups within these multiple tables using the a variable as the title for each row.

Here is a simplification of my code use an example dataset I created. I put in the gt() command to show how I would get these results using that command. The kable command apparently only creates a final product after knitting and unfortunately I don't know how to alter that so that it will print in a regular file. I am open to suggestions using either command to make the data look the way I need it to.

library(gt)
library(kableExtra)
library(knitr)

knitr::opts_chunk$set(echo = TRUE)

county <- c("One", "One", "One", "Two", "Two", "Two", "Three", "Three", "Three", "Four", "Four", "Four")
year <- c("2018", "2019", "2020", "2018", "2019", "2020", "2018", "2019", "2020", "2018", "2019", "2020")
drug1 <- c(1, 2, 3, 1, 2, 3, 1, 2, 3, 1, 2, 3)
drug2 <- c(7, 8, 9, 7, 8, 9, 7, 8, 9, 7, 8, 9)

example <- data.frame(county, year, drug1, drug2)

gt_example <- example %>%
  gt(groupname_col = "county")

print(gt_example)

kable_example<-split(example, rep(1:2, each=6))

#For loop to create the 23 tables
for (i in 1:2){
  print(rbind(kable_example[[i]]) %>% 
          kable("latex", booktabs=TRUE, 
                align=c("l", "l", "r", "r")) %>%
          pack_rows(index = table(kable_example$county)) %>%
          column_spec(2:4, width="1.8cm") %>%
          kable_styling(latex_options=c("repeat_header", "striped")) %>% 
          add_header_above(c("ED Visits for Drug Overdose"=3), bold=TRUE))
}

When I attempt to integrate the pack_rows command, I get the following error message: Error in data.frame(header = header, colspan = 1, row.names = NULL) : arguments imply differing number of rows: 0, 1

Thank you for any assistance or suggestions you can provide me!

mbsteel
  • 1
  • 1
  • I have a similar task ahead of me, but have not yet found the time to look into this. I found this an interesting resource and it might be what you need: https://community.rstudio.com/t/example-large-multi-page-table-table-contest-submission/86381 – Ray Jun 09 '21 at 18:24
  • ^^^ That document was super helpful, thanks for sharing! – mbsteel Jun 11 '21 at 16:49

0 Answers0