glin / reactable

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

Add first/last as one of the built-in aggregate functions for colDef #387

Open C92Anderson opened 1 month ago

C92Anderson commented 1 month ago

Hi @glin,

Wondering if it would be possible to add last() and first() as a built-in aggregate function for colDef()? I'm not sure if the custom JS (which I'm not great with) can work with defaultSorted to make this happen so I'm making a request - thanks!

glin commented 1 month ago

Sure, that seems reasonable. In JS, it would also be relatively straightforward to implement, so a custom aggregate function solution could look like this:

data <- MASS::Cars93[14:38, c("Type", "Price", "MPG.city", "DriveTrain", "Man.trans.avail")]

agg_first <- JS("values => values[0]")
agg_last <- JS("values => values[values.length - 1]")

reactable(
  data,
  groupBy = "Type",
  columns = list(
    Price = colDef(aggregate = agg_first),
    DriveTrain = colDef(aggregate = agg_last)
  )
)

But also just to clarify, these would return the first and last elements of the group before sorting, so sorting won't change the results. If you did need the first and last elements after sorting, that'd be more difficult as grouping/aggregation is currently done before sorting. I'm not sure how feasible it would be to enable a sorting-aware aggregation.

C92Anderson commented 1 month ago

Excellent, thank you on both fronts!

On Sun, Aug 4, 2024 at 11:33 PM Greg Lin @.***> wrote:

Sure, that seems reasonable. In JS, it would also be relatively straightforward to implement, so a custom aggregate function solution could look like this:

data <- MASS::Cars93[14:38, c("Type", "Price", "MPG.city", "DriveTrain", "Man.trans.avail")] agg_first <- JS("values => values[0]")agg_last <- JS("values => values[values.length - 1]")

reactable( data, groupBy = "Type", columns = list( Price = colDef(aggregate = agg_first), DriveTrain = colDef(aggregate = agg_last) ) )

But also just to clarify, these would return the first and last elements of the group before sorting, so sorting won't change the results. If you did need the first and last elements after sorting, that'd be more difficult as grouping/aggregation is currently done before sorting. I'm not sure how feasible it would be to enable a sorting-aware aggregation.

— Reply to this email directly, view it on GitHub https://github.com/glin/reactable/issues/387#issuecomment-2268106154, or unsubscribe https://github.com/notifications/unsubscribe-auth/ACAO5NUQ677WOHGQNIG6TCDZP3XB3AVCNFSM6AAAAABL2X4LVWVHI2DSMVQWIX3LMV43OSLTON2WKQ3PNVWWK3TUHMZDENRYGEYDMMJVGQ . You are receiving this because you authored the thread.Message ID: @.***>