rstudio / crosstalk

Inter-htmlwidget communication for R (with and without Shiny)
http://rstudio.github.io/crosstalk
Other
288 stars 52 forks source link

How to order checkbox filters by number of entries or factor level? #135

Open ulyngs opened 1 year ago

ulyngs commented 1 year ago

Posted this on StackOverflow too:

I'm using checkbox filters to filter a reactable table. By default, the checkboxes are ordered alphabetically. I want to override this, and sort by e.g. number of entries, or by factor level.

Here's a silly reproducible example: Below I've got a dataframe with a bunch of fruits, and a rating for each.

Checkbox options are currently ordered alphabetically. I want to order the checkboxes for 'Fruit type' by number of entries for that type (so banana > pear > apple), and the checkboxes for 'Quality' by factor level (so amazing > okay > awful).

---
title: "Ordering checkboxes from crosstalk"
---

```{r, echo=FALSE, message=FALSE}
library(dplyr)
library(crosstalk)
library(reactable)

fruit_data <- data.frame(fruit = c(rep("apple", 4), rep("banana", 14), rep("pear", 12)),
                         quality = c(rep("awful", 10), rep("okay", 15), rep("amazing", 5))) |> 
  # add a column where the fruit name is followed by how many there are, e.g. "apple (4)"  
  group_by(fruit) |> 
  mutate(fruit_label = paste0(fruit, " (", n(), ")"))

shared_data <- SharedData$new(fruit_data)

filter_checkbox("fruit", "Type", shared_data, ~fruit_label)
filter_checkbox("fruit", "Quality", shared_data, ~quality)

reactable(shared_data,
          columns = list(
            fruit_label = colDef(show = FALSE)
          ))


[![enter image description here][1]][1]

What's the simplest way to do this?

  [1]: https://i.stack.imgur.com/sAcJ2.png