Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Color highlighting text in R for a pre-defined list of words

Suppose I have a collection of documents such as:

text = c("is it possible to highlight text for some words" , 
      "suppose i want words like words to be red and words like text to be blue")

I am wondering whether it is possible to highlight documents (particularly for a large corpus) with colors for a pre-defined list of words using R. Each word in the list will get a specific color. For example, highlighting "words" to be red and "text" to be blue as shown below.

enter image description here

like image 392
Sam S. Avatar asked Oct 26 '25 01:10

Sam S.


1 Answers

Here is the full debugged app code!

First, required libraries:

library(shiny)
library(tidyverse)
library(DT)
library(magrittr)

Then, the function that adds HTML tag:

wordHighlight <- function(SuspWord,colH = 'yellow') {
  paste0('<span style="background-color:',colH,'">',SuspWord,'</span>')
}

Now UI portion:

ui <- fluidPage(
   titlePanel("Text Highlighting"),
   sidebarLayout(
      sidebarPanel(
        textInput("wordSearch", "Word Search")
      ),
    mainPanel(
        DT::dataTableOutput("table")
      )   
   )  
   )

Finally, on the server side:

server <- function(input, output) {
   sentence <- "The term 'data science' (originally used interchangeably with 'datalogy') has existed for over thirty years and was used initially as a substitute for computer science by Peter Naur in 1960."
   sentence2 = "One of the things we will want to do most often for social science analyses of text data is generate a document-term matrix."
   YourData = data.frame(N = c('001','002'), T = c(sentence,sentence2), stringsAsFactors=FALSE)
   highlightData <- reactive({
     if (input$wordSearch!="")
      {
        patterns = input$wordSearch
        YourData2 = YourData
        YourData2[,2] %<>% str_replace_all(regex(patterns, ignore_case = TRUE), wordHighlight)
        return(YourData2)
      }
    return(YourData)
  })
    output$table <- DT::renderDataTable({
      data <- highlightData() 
    }, escape = FALSE)
}

Run the app:

shinyApp(ui = ui, server = server)
like image 177
Ofelia Avatar answered Oct 28 '25 16:10

Ofelia



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!