crosstalk
crosstalk copied to clipboard
How to order checkbox filters by number of entries or factor level?
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)
))
```
What's the simplest way to do this?