Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

gt table - newline in cell

Tags:

newline

r

gt

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

like image 992
Nicolas Rosewick Avatar asked Aug 11 '20 08:08

Nicolas Rosewick


People also ask

How to modify the column labels of a GT table?

Column labels can be modified from their default values (the names of the columns from the input table data). When you create a gt table object using gt (), column names effectively become the column labels.

What is a GT table object?

A table object that is created using the gt () function. ... One or more named arguments of column names from the input .data table along with their labels for display as the column labels. We can optionally wrap the column labels with md () (to interpret text as Markdown) or html () (to interpret text as HTML).

How do I move a column in a table in GT?

There are a number of functions that gt provides to move columns, including cols_move (), cols_move_to_end (); there’s even a function to hide columns: cols_hide (). Multiple columns can be renamed in a single use of cols_label ().

What is the GT table package?

The gt package makes it relatively easy to add parts so that the resulting gt Table better conveys the information you want to present. These table parts work well together and there the possible variations in arrangement can handle most tabular presentation needs.


1 Answers

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

like image 143
zx8754 Avatar answered Sep 20 '22 01:09

zx8754