Search code examples
rkablekableextraquarto

Can cells overflow in kable, kableExtra?


I am simulating a WhatsApp conversation with Kable. Since I have a column for each of the two chatters, long text wraps to fit cells. I'would like the text to overflow to each other chatter's column to better simulate a conversation.

chat <- tibble(
  john = c("looooooooooong sentence1", NA, "looooooooooong sentence2", NA),
  jane = c(NA, "even looooooooooongerrrrrrrrrr sentence1", NA, "even looooooooooongerrrrrr sentence2"))

chat %>% 
  knitr::kable( format = "html", 
                table.attr = "style='width:50%;'",
                align = "lr", 
                col.names = NULL) %>%
  row_spec(which(!is.na(chat$jane)), background = "#DCF8C6")

My Output:
My output

What I want:
What I want

I also set up options(knitr.kable.NA = '') in order to hide NAs


Solution

  • Here's a possible approach using the align argument of row_spec to control the text.

    library(tibble)
    library(knitr)
    library(kableExtra)
    library(tidyr)
    library(dplyr)
    
    # convert table into long format
    chat <- 
      chat |>  
      pivot_longer(everything()) |> 
      na.omit()
    
    chat |> 
      select(value) |> 
      kable( format = "html", 
                    table.attr = "style='width:50%;'",
                    col.names = NULL) |>
      column_spec(1, width = "100mm") |> 
      row_spec(which(chat$name == "jane"), background = "#DCF8C6", align = "r")
    
    

    enter image description here