Search code examples
rdtgtquarto

add return character(s) to a field in DT or gt table?


I am working with quarto to table some results from a qualitative data analysis, and present them in a {DT} or {gt} table.

I have a placeholder character in the table I'm receiving from another data source, but cannot seem to replace that placeholder with one or more carriage returns to make entries easier to read in the resulting DT or gt table.

Thanks for your collective help!

library(tidyverse)
library(DT)
library(gt)

df_text <- tibble::tibble(index = c("C-1", "C-2"),
                          finding = c("A finding on a single line.", "A finding with a return in the middle.<return>Second line is usually some additional piece of context or a quote.")) %>% 
  dplyr::mutate(finding = stringr::str_replace_all(finding, "<return>", "\\\n\\\n"))

DT::datatable(df_text)

gt::gt(df_text)

Solution

  • for gt you need

    gt::gt(df_text) |> tab_style(style=cell_text(whitespace = "pre"),
                                 locations=cells_body())
    

    for DT you could modify the column with the required text to be html and then tell DT to respect your HTML

    df_text <- tibble::tibble(index = c("C-1", "C-2"),
                              finding = c("A finding on a single line.", "A finding with a return in the middle.<return>Second line is usually some additional piece of context or a quote.")) %>% 
      dplyr::mutate(finding = paste0("<HTML>",
                                     stringr::str_replace_all(finding, "<return>", "</br></br>"),
                                     "</HTML>"))
    
    DT::datatable(df_text,escape = FALSE)