I have a datatable in R Shiny, and one of the columns, Keywords, contains multiple entries for some rows, separated by a comma. I would like these multiple entries to be individually searchable. The default search feature for datatable treats these entries as one, long, single item.
For example, row 2's value for the column Keywords is "Keyword1, Keyword2". I would like the user to be able to search for either "Keyword1" OR "Keyword2" and find row 2. Currently, the default search bar in datatable treats this entry as one item: "Keyword1, Keyword2" and only allows people to search for "Keyword1, Keyword2" as one, joint item, not two separate values.
Here is a small, reproducible example of the problem
library(shiny)
library(DT)
## Create an example dataset with 3 rows and 1 column
dat <- matrix(c("Keyword1", "Keyword1, Keyword2", "Keyword2"), nrow = 3, ncol = 1)
colnames(dat) <- "Keywords"
dat <- data.frame(dat)
ui <- shinyUI(
DT::dataTableOutput('ex1')
)
server <- shinyServer(function(input, output) {
output$ex1 <- DT::renderDataTable(
DT::datatable(dat, filter = "top")
)
})
shinyApp(ui = ui, server = server)
Perhaps you can try something like this:
keys <- c("Keyword1", "Keyword1, Keyword2", "Keyword2")
grepl(paste("Keyword1", collapse = "|"), keys)
#output
[1] TRUE TRUE FALSE
grepl(paste("Keyword2", collapse = "|"), keys)
#output
[1] FALSE TRUE TRUE
Since I do not have any code to reproduce, I just came up with this example which you can extend to the datatable in shiny using the user inputs.
In your case you can do something like:
filter <- grepl(paste(input$keys, collapse = "|"), data$keywords)
I am assuming keys is the ID for the user input box and keywords is the column in the datatable data. You can then use filter to subset your data accordingly.
EDIT:
The problem, atleast with the sample dataset and assuming the same in your case, is that the column which has a filter is a Factor. If you convert the column to a Character using as.character(), your code will work fine. When you search for keyword1 in the filter, it will result in only those rows that have keyword1 in them.
library(shiny)
library(DT)
## Create an example dataset with 3 rows and 1 column
dat <- matrix(c("Keyword1", "Keyword1, Keyword2", "Keyword2"), nrow = 3, ncol = 1)
colnames(dat) <- "Keywords"
dat <- data.frame(dat)
dat$Keywords <- as.character(dat$Keywords)
ui <- shinyUI(
DT::dataTableOutput('ex1')
)
server <- shinyServer(function(input, output) {
output$ex1 <- DT::renderDataTable(
DT::datatable(dat, filter = "top")
)
})
shinyApp(ui = ui, server = server)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With