reactable icon indicating copy to clipboard operation
reactable copied to clipboard

How to let javascript calculate both grouped rows totals and subgroup totals?

Open rdatasculptor opened this issue 5 years ago • 3 comments

This issue is related to this one.

I know I should try to find out myself, but what If I need to calculate the totals of both grouped rows and their subgroups. And additional to that the column totals in the footer. Maybe you can point me in the right direction?

This example will illustrate what I mean. Instead of the built in aggreation functions I want to use their equivalents in javascript (and with an addtional column total):

data <- data.frame(
  State = state.name,
  Region = state.region,
  Division = state.division,
  Area = state.area
)

reactable(
  data,
  groupBy = c("Region", "Division"),
  columns = list(
    Division = colDef(aggregate = "unique"),
    Area = colDef(aggregate = "sum", format = colFormat(separators = TRUE))
  ),
  bordered = TRUE
)

Many thanks in advance!

rdatasculptor avatar Jun 23 '20 10:06 rdatasculptor

Do you mean the total of all individual values in the column? Here's a way to do that, based on the example I just added to https://github.com/glin/reactable/issues/50#issuecomment-650924550. The totals of all values in a row's subgroup will be available in the row data:

data <- data.frame(
  State = state.name,
  Region = state.region,
  Division = state.division,
  Area = state.area
)

reactable(
  data,
  groupBy = c("Region", "Division"),
  columns = list(
    Division = colDef(aggregate = "unique"),
    Area = colDef(
      aggregate = "sum",
      format = colFormat(separators = TRUE),
      footer = JS("function(colInfo) {
        var total = 0
        colInfo.data.forEach(function(row) {
          total += row[colInfo.column.id]
        })
        // Use toLocaleString to add thousands separators
        return total.toLocaleString()
      }")
    )
  ),
  bordered = TRUE
)

screenshot of table output

If this isn't what you meant, could you provide an example of the expected output perhaps?

glin avatar Jun 29 '20 06:06 glin

Just a side question: Would it be possible to remove the row counts (e.g in example above have South without the number 3.)

amanthapar avatar Aug 31 '20 18:08 amanthapar

@amanthapar That's not possible today, but it likely will be in the future.

glin avatar Sep 05 '20 16:09 glin