Highlight Predefined Words in Shiny DT table [Not through Search Highlight] [closed]

泄露秘密 提交于 2019-12-05 09:34:45

问题


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

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?


回答1:


You can use tableHTML for that:

library(tableHTML)

The mtcars dataset is use throughout this answer:

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

The result is:

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

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

Create the basic tableHTML object:

tableHTML <- mtcars %>% 
  tableHTML() 

And apply the css word for word using a loop:

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

The result is:

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

The result is:



来源:https://stackoverflow.com/questions/51474117/highlight-predefined-words-in-shiny-dt-table-not-through-search-highlight

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!