gt table - newline in cell
Asked Answered
S

1

13

I try to force a newline in a gt cell using R gt package. In gt documentation it is described as possible to do it for column labels using cols_label()

 # example
 gt_tbl %>%
  cols_label(
    col = html("text1,<br>text2")
   )

But in cells I could not find a way to do it. I tried by adding \n or
without success.

library(gt)

# dummy data
dat <- tibble(
  a=1:3,
  b=c("a","b c","d e f")
)

# A tibble: 3 x 2
      a b    
  <int> <chr>
1     1 a    
2     2 b c  
3     3 d e f

# with \n
dat %>% 
  mutate(b=str_replace_all(b," ","\n")) %>% 
  gt()

# with <br>
dat %>% 
  mutate(b=str_replace_all(b," ","<br>")) %>% 
  gt()

Always the same table that is generated :

enter image description here

Expected results :

enter image description here

Any ideas ?

Thank you

Seyler answered 11/8, 2020 at 8:55 Comment(0)
C
27

We need to call fmt_markdown, see below:

Any Markdown-formatted text in the incoming cells will be transformed to the appropriate output type during render when using fmt_markdown().

dat %>% 
  mutate(b = str_replace_all(b, " ", "<br>")) %>% 
  gt() %>% 
  fmt_markdown(columns = TRUE)

enter image description here


Or a workaround: split into new rows then call gt():

dat %>% 
  separate_rows(b) %>% 
  mutate(a = ifelse(duplicated(a), "", a)) %>% 
  gt()

enter image description here

Congo answered 11/8, 2020 at 9:21 Comment(1)
New syntax in 0.3.0 is fmt_markdown(columns = everything()) or some other select helper (starts_with("xyz")Altair

© 2022 - 2024 — McMap. All rights reserved.