Search code examples
rr-markdownkablekableextra

How to split row from table if column exceeds the page capacity in R Markdown?


Below I have a script that contains a 5th text column that had so much written it exceeded the size of the page. Though I added longtable = T and latex_options= "repeat_header" it only continues the table through multiple pages but if the row exceeds the page it gets cut off. How can I keep the table moving along while not losing text.

df %>%
kableExtra::kbl(.,booktabs = T,longtable = T)%>%    
row_spec(0,background = "#F6F6F6",color="black")%>%
kable_styling(bootstrap_options = "striped", font_size = 9,latex_options = 
c("hold_position","repeat_header"),position = "left") %>%
column_spec(1,width = "2.0cm") %>%
column_spec(2,width = "2.5cm") %>%
column_spec(3,width = "2.5cm") %>%
column_spec(4,width = "4.5cm")%>%
column_spec(5,width="10.0cm")

Solution

  • Here's a workaround by splitting the cell with long text. It works by splitting the text into two chunks based on word count so could easily be adjusted by trial and error.

    ```{r setup, include=FALSE}
    
    knitr::opts_chunk$set(echo = FALSE)
    
    library(kableExtra)
    library(wakefield) # for generating long text
    library(dplyr)
    library(tidyr)
    library(stringr)
    
    ```
    
    ```{r df, include=FALSE}
    
    set.seed(123)
    
    #sample dataset
    
    df <- data.frame(a = 1:6,
                     b = month.name[1:6],
                     c = names(mtcars)[1:6],
                     d = names(islands)[1:6],
                     e = c(paragraph(2), paste(paragraph(6), collapse = "; "), paragraph(3)))
    
    #create new data frame, cells with long text split into to
    df_new <- 
      df %>% 
      mutate(f = ifelse(str_length(e)>2000, word(e, 301, -1), NA_character_),
             e = ifelse(str_length(e)>2000, word(e, 1, 300), e)) %>% 
      pivot_longer(cols = c(f, e), values_to = "e") %>% 
      na.omit() %>% 
      arrange(a, name) %>% 
      select(-name)
    
    ```
    
    ```{r long-table, results='asis'}
    
    df_new %>%
    kbl(booktabs = TRUE, 
        longtable = TRUE) %>%
      row_spec(0, background = "#F6F6F6", color = "black") %>%
      landscape() %>%
      kable_styling(bootstrap_options = "striped",
                  font_size = 9,
                  latex_options = c("hold_position","repeat_header"),position = "left") %>%
      column_spec(1, width = "2.0cm") %>%
      column_spec(2, width = "2.5cm") %>%
      column_spec(3, width = "2.5cm") %>%
      column_spec(4, width = "4.5cm") %>%
      column_spec(5, width = "10.0cm")
    
    ```