在闪亮的DT表中突出显示预定义的单词[不通过搜索突出显示] [英] Highlight Predefined Words in Shiny DT table [Not through Search Highlight]

查看:74
本文介绍了在闪亮的DT表中突出显示预定义的单词[不通过搜索突出显示]的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在创建一个闪亮的应用程序,我想突出显示DT表中的某些预定义单词。我知道DT中的搜索突出显示功能。例如:

I'm creating a shiny application and I want to highlight certain predefined words in DT table in shiny. I'm aware of the search highlight feature in DT. For example:

datatable(mtcars2, options = list(searchHighlight = TRUE, search = list(search = 'da')))

我想像前面的示例一样突出显示,但不是通过搜索 。例如,在 mtcars 数据中,我要突出显示'Merc','Fiat','Honda'单词,而不在 search 中提供的桌子。表格一出现,字词就会突出显示,而不是整个单元格。

I want to highlight like the previous example but not from a search. For say, in mtcars data, I want to highlight words 'Merc', 'Fiat', 'Honda' without providing it in the search of the table. As soon as the table appears, the words will be highlighted, not the entire cell.

有没有办法做到这一点?

Is there a way to do that?

推荐答案

您可以为此使用 tableHTML

library(tableHTML)

mtcars 数据集在整个答案中一直使用:

The mtcars dataset is use throughout this answer:

使用<创建一个 tableHTML 对象code> tableHTML()函数。如果列(在本例中为行名,即索引 0 包含,则应用条件CSS。所应用的css只是使用黄色突出显示背景:

Create a tableHTML object using the tableHTML() function. Then apply conditional css, if the column (in this case the rownames, i.e. index 0) contains a specific word. The css that is applied is simply highlighting the background using yellow:

mtcars %>% 
  tableHTML() %>% 
  add_css_conditional_column(columns = 0,
                             conditional = "contains",
                             value = "Toyota",
                             css = list(c("background-color"),
                                        c("yellow")))

结果是:

如果要匹配许多单词,则可以创建单词向量:

In case of many words that should be matched, you can create a vector of words:

words <- c("Merc", "Fiat", "Honda")

创建基本的 tableHTML 对象:

tableHTML <- mtcars %>% 
  tableHTML() 

for (word in words) {
  tableHTML <- tableHTML %>% 
    add_css_conditional_column(columns = 0,
                               conditional = "contains",
                               value = word,
                               css = list(c("background-color"),
                                          c("yellow")))
}

结果是:

如果您只想突出显示某个子字符串,则可以修改数据,并在子字符串周围包含 span 并在其中应用CSS。

If you only want to highlight a certain substring, you could modify the data and include a span around the substring and apply css there.

library(magrittr) # for the %<>% pipe

rownames(mtcars) %<>% 
  stringr::str_replace_all(c('Merc' = '<span style="background-color:yellow">Merc</span>',
                  'Fiat' = '<span style="background-color:yellow">Fiat</span>',
                  'Honda' = '<span style="background-color:yellow">Honda</span>'))


mtcars %>% 
  tableHTML()

结果是:

这篇关于在闪亮的DT表中突出显示预定义的单词[不通过搜索突出显示]的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆