rstudio / DT

R Interface to the jQuery Plug-in DataTables
https://rstudio.github.io/DT/
Other
599 stars 180 forks source link

Keyword Filtering in Dropdown Filter Menus? #1154

Closed maryjewell closed 1 month ago

maryjewell commented 1 month ago

I am working on a table where one column may contain one or more option, like the one below:

image

test_df <- data.frame(student = c("Amy", "Jacky", "Peter"),
                      fruit_like = as.factor(c("Apple, Banana", "Orange", "Apple")))

DT::datatable(test_df, filter = "top")

I am wondering if there is a way for a user to search for any one item in a list and filter for all rows that contain that item, even if they also contain other items. For example, in the table above, a user should be able to search "Apple" and get both Amy and Peter. As it is, users can only search for the exact combinations that appear in each row, as seen below:

image

This question has been asked a few times on StackOverflow, as far as I can see (here and here) but I have not seen any workable answers. Is it possible with DT tables to enable keyword filtering? Thank you for any help.


By filing an issue to this repo, I promise that

I understand that my issue may be closed if I don't fulfill my promises.

yihui commented 1 month ago

If you don't convert the fruit_like column to factor but leave it as character, you should be able to partially match the items.

maryjewell commented 1 month ago

Thanks for this advice! Yes, I've seen that filtering on a text field allows me to search for individual items, but the problem with that is that a user couldn't search for multiple items at a time. For example, if a user wanted to search for all rows that contained apples and/or oranges in the table above, using the text filter with "apples, oranges" or "apples|oranges" doesn't yield any results. In that case, they would need to search for apples and then, separately, oranges, which is less ideal for my use case.

yihui commented 1 month ago

You can enable regex as suggested by the SO answer https://stackoverflow.com/a/49785617/559676:

test_df <- data.frame(student = c("Amy", "Jacky", "Peter"),
                      fruit_like = c("Apple, Banana", "Orange", "Apple"))

DT::datatable(test_df, filter = "top", options = list(search = list(regex = TRUE)))

Then you can use the keyword apple|orange to match records that contain either apple or orange.

maryjewell commented 1 month ago

Thanks! This should work well enough.