glin / reactable

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

Aggregated row indexes #224

Closed tanho63 closed 2 years ago

tanho63 commented 2 years ago

Hiya! Incredibly grateful for reactable. Ran into an issue and wondering if you might have some thoughts on how to solve:

I'm trying to add a ranking (aka row index) column to an aggregated table (specifically https://ep.dynastyprocess.com) which uses crosstalk and JS-based aggregations to filter/summarize data. I've managed to figure out how to add it to an ungrouped table as follows:

library(reactable) # glin/reactable@v0.2.3.9000
library(dplyr)

mtcars %>%
  mutate(rank = "a") %>%
  select(rank,everything()) %>%
  reactable(
    filterable = TRUE,
    columns = list(
      rank = colDef(
        name = "Rank",
        cell = JS(
          "function(cellInfo, state){
          return Number(cellInfo.viewIndex) + Number(state.page) * Number(state.pageSize) + 1
          }"
        ),
        html = TRUE
      )
    )
  )

which creates a new column that responds to sorting/filtering and renumbers the indices. I'm not sure how to recreate the same thing with an aggregated table - i think the viewIndex for aggregated data isn't part of the JS object?

mtcars %>%
  mutate(rank = "a") %>%
  select(rank,everything()) %>%
  reactable(
    groupBy = "cyl",
    columns = list(
      rank = colDef(
        name = "Rank",
        aggregate = JS(
          "function(cellInfo, state){
          return Number(cellInfo.viewIndex) + Number(state.page) * Number(state.pageSize) + 1
          }"
        ),
        html = TRUE
      )
    ),
    filterable = TRUE,
    defaultColDef = colDef(aggregate = "sum")
  )

Grateful for any guidance!

glin commented 2 years ago

Hi, this is probably because there are two poorly named arguments named aggregate and aggregated. aggregate is the data aggregation function (see custom aggregate function). aggregated is the aggregated cell render function with the viewIndex property. If you change the argument name to aggregated, it should work as expected.

If I could go back, I would've probably named these something like aggregateFunc and aggregatedCell to be less confusing, but we're stuck with these names for now 😅

tanho63 commented 2 years ago

🤯 welp, that'll do it!

mtcars %>%
  mutate(rank = "a") %>%
  select(rank,everything()) %>%
  reactable(
    groupBy = "cyl",
    columns = list(
      rank = colDef(
        name = "Rank",
        aggregated = JS(
          "function(cellInfo, state){
          return Number(cellInfo.viewIndex) + Number(state.page) * Number(state.pageSize) + 1
          }"
        ),
        html = TRUE
      )
    ),
    filterable = TRUE,
    defaultColDef = colDef(aggregate = "sum")
  )

image

Fantastic, thank you so much!