如何在R tablehtml中突出显示某些字符串?

时间:2018-08-14 07:30:57

标签: r highlight tablehtml

这就是我想要的

Please click to see the screenshot

这是我在Clemens帖子之后的代码

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

有人可以帮忙吗?谢谢。

1 个答案:

答案 0 :(得分: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更改字体颜色。

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)

结果是:

output