Search code examples
rr-markdownpdflatexkable

Kable printing table above heading in Rmarkdown


Using the following extract from my Rmarkdown

for (swimmer in swimmers) {
  cat('\\newpage')
  cat('## ', swimmer, '\n\n')
  
  dtEvents <- dtClub[name == swimmer, ][order(event)]
  
  for (r in 1:nrow(dtEvents)) {
    row <- dtEvents[r,]
    title <- paste0('Event ', row$event, ' ', row$race_gender, ' ', row$age_group, ' ', row$distance, ' ', row$stroke)

    dtRace <- dt[event == row$event & seed %between% c(row$seed-5, row$seed+5)][order(seed)]

    cat(kbl(dtRace[, .(seed, name, age, club, seed_time_str, seed, heat, lane)],
        align = c('r','l','c','l','r','r','r','r'), caption = title, longtable = FALSE) %>%
      kable_styling(latex_options = c('striped','scale_down','repeat_header')))
    cat('\n')
  }
}

I'm ending up with the heading of the person's name printing underneath the tables on the first page rather than above them. I get a page break per person and all the data in tables, just the heading with their name is below all tables of data on their first page with remaining tables following on further pages.

Edit: On further inspection it appears the \newpage is not working at all. \pagebreak doesn't seem to work either.


Solution

  • I found that by using the information in this answer I was able to solve the problem. As a complete noob to kable/latex I wasn't aware of how tables are positioned within the document.

    By adding kable_styling(latex_options = "HOLD_position") to the kable statement everything worked as required. There was also the odd part around making sure to use '\n' in the correct places when outputting latex statements in the R code else it gets a little upset.