如何突出显示 R tablehtml 中的某些字符串?
How to highlight certain strings in R tablehtml?
这就是我想要的
这是我遵循 Clemens post
的代码
library(magrittr)
sample1$sentence %<>%
stringr::str_replace_all(c('red' = '<span style="background- color:blue">red</span>'))
sample1 %>%
tableHTML()
有人可以帮忙吗?谢谢
使用的包:
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)
结果是:
这就是我想要的
这是我遵循 Clemens post
的代码library(magrittr)
sample1$sentence %<>%
stringr::str_replace_all(c('red' = '<span style="background- color:blue">red</span>'))
sample1 %>%
tableHTML()
有人可以帮忙吗?谢谢
使用的包:
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)
结果是: