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

Time:09-03

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)

CodePudding user response:

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)

CodePudding user response:

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")
  }
}
  • Related