Conditional highlighting of rows in tableHTML

407 Views Asked by At

In tableHTML: Is there a way to highlight complete rows based on one conditional column? Something like this, but also with red cells in the mpg-, cyl- and disp-columns:

tableHTML(mtcars[1:10,1:3]) %>%
add_css_conditional_column(conditional = "contains", 
                           value = "Hornet",
                           css = list('background-color', "red"), 
                           columns = "rownames")
3

There are 3 best solutions below

2
On BEST ANSWER

In the recently published version of tableHTML (version 2.1.0), there's an option to choose logical as a conditional type with add_css_conditional_column, which can be also used as a proxy for row conditional highlighting if it was applied to all columns

Basically you define the logical vector for the condition (just like the answer by clemens), and choose to apply it to all columns like so:

my_df <- mtcars[1:10,1:3]
conditional <- grepl("Hornet", rownames(my_df)) 

tableHTML(my_df) %>%
  add_css_conditional_column(conditional = "logical", 
                             columns = 0:ncol(my_df),
                             css = list('background-color', "red"), 
                             logical_conditions = list(conditional))

enter image description here

0
On

I found an answer myself. Using the add_css_row function, the condition can be added to the rows parameter:

my_df <- mtcars[1:10,1:3]
tableHTML(my_df) %>%
add_css_row(css = list('background-color', 'red'), 
            rows = grep("Hornet", rownames(my_df)) + 1)

enter image description here

0
On

We have the intention to include that functionality in the package, but haven't implemented it yet. It can be done with a bit of a hack though:

First, we create a logical vector for the conditional, then we create a tableHTML object. Then, for each column in the tableHTML object, we can apply a style in a loop using the function add_css_rows_in_column:

library(tableHTML)

conditional <- grepl("Hornet", rownames(mtcars[1:10, ])) 

my_tableHTML<- mtcars[1:10,1:3] %>% 
 tableHTML()
for (i in 0:3) {
 my_tableHTML <- my_tableHTML %>% 
  add_css_rows_in_column(css = list(c("background-color"), 
                                    ifelse(conditional, "red", "")),
                         column = i)
} 

my_tableHTML

The result looks like this: tableHTML_result