glin / reactable

Interactive data tables for R
https://glin.github.io/reactable
Other
633 stars 80 forks source link

Merge rows within column #13

Closed Spswitzer closed 4 years ago

Spswitzer commented 4 years ago

I would like to merge two values in one column similar to options = list( rowsGroup = list(0))

in the DT package.

Can anyone support me with the proper syntax for this request?

glin commented 4 years ago

Cell merging isn't supported, and would unfortunately be difficult to implement right now. The next version of the underlying React Table library (still in beta) will make it easy to merge cells, but reactable probably won't be upgrading for a while.


However, you could still fake the appearance of merged cells by conditionally hiding cells in a group. For example, if the previous row is in the same group, render blank content or hide the cell using a visibility: hidden style.

If the table is completely static (can't be sorted, filtered, etc), you could do this all in R for simplicity. But if the table can be sorted, filtered, or paginated, you'll have to use a JavaScript render function or style function to only hide cells when sorting on that group. I've added an example of this to the demo cookbook: https://glin.github.io/reactable/articles/cookbook/cookbook.html#merge-cells

library(dplyr)

data <- as_tibble(MASS::painters, rownames = "Painter") %>%
  filter(School %in% c("A", "B", "C")) %>%
  mutate(School = recode(School, A = "Renaissance", B = "Mannerist", C = "Seicento")) %>%
  select(School, Painter, everything()) %>%
  group_by(School) %>%
  slice(1:3)

reactable(
  data,
  columns = list(
    School = colDef(
      style = JS("function(rowInfo, colInfo, state) {
        var firstSorted = state.sorted[0]
        // Merge cells if unsorted or sorting by school
        if (!firstSorted || firstSorted.id === 'School') {
          var prevRow = state.pageRows[rowInfo.viewIndex - 1]
          if (prevRow && rowInfo.row['School'] === prevRow['School']) {
            return { visibility: 'hidden' }
          }
        }
      }")
    )
  ),
  outlined = TRUE
)

screenshot of table

Spswitzer commented 4 years ago

Thanks for your support. The JS script that you provided is a workable solution.