How to highlight certain strings in R tablehtml?

354 Views Asked by At

This is what I want

Please click to see the screenshot

Here is my code following Clemens post

library(magrittr)
sample1$sentence %<>% 
stringr::str_replace_all(c('red' = '<span style="background- color:blue">red</span>'))
sample1 %>% 
tableHTML()

Can anyone please help? Thanks.

1

There are 1 best solutions below

1
On BEST ANSWER

The packages used:

library(dplyr)
library(tableHTML)

The sample data:

sample1 <- data.frame(words = c("interested", "red", "black"),
                      sentence = c("I am very interested in this topic",
                                   "Multiple color: red, blue, black",
                                   "multiple color: red, blue, black"),
                      stringsAsFactors = FALSE)

Create a list to store words and the colour you want to apply to them:

word_colour <- list(interested = "red",
                    red = "blue",
                    black = "purple")

The function below uses the word_colour, looks for the word in the sentence and adds a span around it with inline CSS that changes the font colour.

replace_word <- function(word_colour, df) {
  word <- df$words
  sentence <- df$sentence

  stringr::str_replace(string = sentence,
                       pattern = word,
                       replacement = paste0('<span style="color:', 
                                            word_colour[[word]], 
                                            '">',
                                            word,
                                            '</span>'))

  }

You can then chain it all together. Important note: rowwise allows you to go through the data row by row. do() is used as a general purpose manipulation function.

sample1 %>% 
  rowwise %>% 
  do({
    df = as_data_frame(.)
    df$sentence = replace_word(word_colour, df)
    df
  }) %>% 
  tableHTML(rownames = FALSE,
            escape = FALSE)

The result is:

output