我在 R Shiny 中有一个数据表,其中一列“关键字”包含某些行的多个条目,以逗号分隔。我希望这些多个条目可以单独搜索。 datatable 的默认搜索功能将这些条目视为一个长的单个项目。
例如,第 2 行的关键字列的值为“关键字 1,关键字 2”。我希望用户能够搜索“Keyword1”或“Keyword2”并找到第 2 行。目前,数据表中的默认搜索栏将此条目视为一个项目:“Keyword1,Keyword2”并且只允许人们搜索对于“Keyword1,Keyword2”作为一个联合项,而不是两个单独的值。
这是该问题的一个可重现的小例子
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)
最佳答案
也许你可以尝试这样的事情:
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
由于我没有任何代码可以重现,所以我只是想出了这个示例,您可以使用用户输入将其扩展到 shiny 中的数据表。
在您的情况下,您可以执行以下操作:
filter <- grepl(paste(input$keys, collapse = "|"), data$keywords)
我假设 keys
是 ID
对于用户输入框和keywords
是数据表中的列 data
.然后您可以使用 filter
相应地对您的数据进行子集化。
编辑:
至少对于示例数据集并假设您的情况相同,问题是具有过滤器的列是 Factor
.如果将该列转换为 Character
使用 as.character()
,您的代码将正常工作。当您搜索 keyword1
时在过滤器中,它只会产生那些具有 keyword1
的行在他们中。
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)
关于r - 在具有多个条目的 R Shiny 数据表中搜索列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42398103/