It is possible to add a general search box for the user to find a string in an output widget in Shiny? In the example below, I would like the user to type a string in the textInput
widget and have Shiny highlight the matching text in the verbatimTextOutput
(or something similar):
library(shiny)
text <- "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Fusce nec quam ut tortor interdum pulvinar id vitae magna. Curabitur commodo consequat arcu et lacinia. Proin at diam vitae lectus dignissim auctor nec dictum lectus. Fusce venenatis eros congue velit feugiat, ac aliquam ipsum gravida. Cras bibendum malesuada est in tempus. Suspendisse tincidunt, nisi non finibus consequat, ex nisl condimentum orci, et dignissim neque est vitae nulla."
ui <- fluidPage(
sidebarPanel(
textInput("search", "", placeholder = "Search term")
),
verbatimTextOutput("text")
)
)
server <- function(input, output) {
output$text <- renderText(paste(text))
}
shinyApp(ui = ui, server = server)
So far, I have been working around this problem by splitting the text in fixed-length rows and using grep
to display the location of the string in the text. (For example, alerting the user that the string lorem
is in the first line).
Can it somehow be done more intuitively?
Edit
@Aurèle's answer is spot on. DT::dataTableOutput
also provides a searchbox feature for finding strings in data.tables, without the higlighting.
Here is my naive attempt (does it satisfy the requirement of it being more intuitive?):
The keys are
str_locate_all()
andstr_sub<-
.(you might want to use
coll()
instead offixed()
, and maybe replacestringr
withstringi
, I have no idea if the performance impact would be measurable).I used @bartektartanus' (co-author of
stringi
) answer here, btw I asked in a comment whether there is a cleaner way than this naivereduce()
.Edit
Actually, I have no idea why I made it so complicated. This is (much) simpler (though it behaves a little differently wrt regexes):