您可以创建一个而不是依赖数据表的搜索功能reactive
首先按输入进行过滤,然后用嵌入在 a 中的相同单词替换匹配单词的元素<span style="background-color:yellow;">
标签。这应该可以通过更复杂的正则表达式提供更大的搜索灵活性。
你需要添加escape = F
to datatable
所以 HTML 标签被正确解释。我已经添加options = list(dom = "lt")
to datatable
删除数据表搜索字段并将注意力转移到左侧搜索字段。
过滤标准相当模糊,以防止表格消失,直到找到完美匹配 - 即,当您键入“o”时,表格不应消失,因为没有完美匹配,然后在“on”处重新出现。仅当找到匹配的单词时才会出现突出显示,即on
, On
, and on.
, 但不是stone
, scone
等等。下面是它的外观:
这是代码。请注意,我使用 dplyr 的过滤和变异函数,因为它们可以通过它们的*_all
变种:
library(shiny)
library(DT)
library(data.table)
library(dplyr) # For `filter_all` and `mutate_all`.
example_data <- iris
# data.table(words = c("on", "scone", "wrong", "stone"),
# description = c("The word on", "Scone is not on.", "Not on either", "Not here at all"))
ui = shinyUI(fluidPage(
sidebarLayout(
sidebarPanel(
textInput("word_select", label = "Word to search")
),
mainPanel(
dataTableOutput("word_searched")
)
)
))
server = shinyServer(function(input, output, session) {
# This is your reactive element.
df_reactive <- reactive({
example_data %>%
# Filter if input is anywhere, even in other words.
filter_all(any_vars(grepl(input$word_select, ., T, T))) %>%
# Replace complete words with same in HTML.
mutate_all(~ gsub(
paste(c("\\b(", input$word_select, ")\\b"), collapse = ""),
"<span style='background-color:yellow;'>\\1</span>",
.,
TRUE,
TRUE
)
)
})
# Render your reactive element here.
output$word_searched <- renderDataTable({
datatable(df_reactive(), escape = F, options = list(dom = "lt"))
})
})
shinyApp(ui = ui, server = server)