-1

If I have a table that looks like this:

enter image description here

How can I merge each group in Column 1 so that the values are not repeated like this:

enter image description here

I also need this to work with the gt table library

I have tried df %>% group_by(Column 1) %>% gt(), but that puts the group above the row instead of merging the cells

TomJones
  • 15
  • 3
  • Does this answer your question? [Grouping Rows in GTSummary](https://stackoverflow.com/questions/65665465/grouping-rows-in-gtsummary) – Panagiotis Togias Apr 22 '23 at 21:17
  • @PanagiotisTogias - No, it does not – TomJones Apr 22 '23 at 21:34
  • @jpsmith - gt and html – TomJones Apr 22 '23 at 21:48
  • 1
    You are asking for Excel concepts to be replicated in R structures. For "merged cells" there is no equivalent. You might get a display that looks like a merged cell but there won't be an underlying structure that is faithful to the Excel concept. – IRTFM Apr 22 '23 at 22:33

2 Answers2

1

We could use flextable:

library(flextable)
library(dplyr)

flextable(df) %>% 
  merge_v(j="Column1") %>% 
  theme_box() %>% 
  align(j = 1, align = "center")

enter image description here

TarJae
  • 72,363
  • 6
  • 19
  • 66
1

Closest thing I can give to what you want is with the below code by removing the top border in cases where the grouped variable is set to an empty character. What is left is to find a way to align each group to the center of each respective area but maybe you're ok with just that.

library(dplyr)
library(gt)

is_empty <- function(x){
  
  return(ifelse(x == "", TRUE, FALSE))
  
}

tibble(colA = c("A", "A", "B", "B", "C", "C"), 
       colB = c("1", "23", "245", "123", "134", "98"),
       colC = c("342", "34", "45", "23", "13", "982")) |> 
  group_by(colA) |> 
  mutate(colA = ifelse(row_number() == 1, colA, "")) |> 
  ungroup() |> 
  gt() |>
  tab_style(
    style = list(
      cell_borders(
        sides = c("top", "bottom"),
        weight = px(0)
      )),
    locations = list(
      cells_body(
        columns = colA,
        rows = is_empty(colA)
      )
    )
  )

enter image description here