Searching Columns in R shiny Datatable that has Multiple Entries

老子叫甜甜 提交于 2021-02-11 11:24:16

问题


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)

回答1:


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)


来源:https://stackoverflow.com/questions/42398103/searching-columns-in-r-shiny-datatable-that-has-multiple-entries

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!