使用DT在shiny中,我想要能够突出显示所选单词。设置
示例图像: 我可以调整搜索选项,使
示例(包括正则表达式):
searchHighlight = TRUE
接近我想要的效果,但这也会突出显示包含搜索的单词。例如,如果我正在搜索“on”,它还将匹配“stone”,并突出显示中间的“on”。示例图像: 我可以调整搜索选项,使
regex = TRUE
,但是然后就不会发生高亮显示。如果我想使用正则表达式比如“on|in”,这也是正确的。示例(包括正则表达式):
library(shiny)
library(DT)
library(data.table)
example_data <- 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) {
output$word_searched <- renderDataTable({
datatable(
example_data,
options = list(searchHighlight = TRUE,
search = list(regex = TRUE,
search = paste0("\\b", tolower(input$word_select), "\\b")))
)
})
})
shinyApp(ui = ui, server = server)
DT已经通过反应表达式过滤了该单词,因此所有字段肯定都包括所选单词,但我只是想避免用户误认为搜索错误地包括了更长的单词而产生混淆。虽然在示例中我还没有这样做,但只是确认这不是我关心的元素。
感谢您的帮助。
(编辑以添加一个在示例数据中带有标点符号的单词示例。)
example_data_dt[, lapply(.SD, function(x) gsub( paste0("\\b(", input$word_select, ")\\b"), "<span style='background-color:yellow;'>\\1</span>", x, TRUE, TRUE ))]
- Jaccar