0

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)
M. Wood
  • 450
  • 4
  • 13

2 Answers2

1

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)
Nir Graham
  • 2,567
  • 2
  • 6
  • 10
  • That's exactly what the doctor ordered! Gives me ideas on where to start looking into DT options too. – M. Wood Sep 02 '22 at 16:28
  • This feels like a lead for DT, but I can't find a reference for the param name etc. in R implementation: https://datatables.net/forums/discussion/43122/space-in-fields – M. Wood Sep 02 '22 at 16:43
  • thanks @nir, for DT I can wrap that mutate in a function and call it before I pipe into `datatable()` call – M. Wood Sep 02 '22 at 18:05
0

Based on @Nir Graham's answer, I wrote a function. The type = "dt" isn't working for some reason, but Nir's recommendation to dplyr::mutate() inline does :shrug:

fx_add_returns <- function(x, type = c("dt", "gt")) {
  type <- match.arg(type)
  
  if (type == "dt"){
    paste0("<HTML>", 
           stringr::str_replace_all(x, "<return>", "</br></br>"), "</HTML>")
  }
  
  if (type == "gt"){
    stringr::str_replace_all(x, "<return>", "\\\n\\\n")
  }
}
M. Wood
  • 450
  • 4
  • 13