0

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.

4

1 回答 1

2

使用的包:

library(dplyr)
library(tableHTML)

样本数据:

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)

创建一个列表来存储单词和要应用于它们的颜色:

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

下面的函数使用word_colour, 查找句子中的单词并在其span周围添加一个带有CSS改变字体颜色的 inline 。

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>'))

  }

然后,您可以将它们链接在一起。重要提示:rowwise允许您逐行浏览数据。do()用作通用操作函数。

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

结果是:

输出

于 2018-08-14T13:14:22.043 回答