'Highlight DT diagonal in R Shiny

I have a large datatable in a Shiny app and would like to highlight the diagonal, using logic something like if rowNum == colNum then 'blue' else 'white'.

The rowCallback DT option would let me style by row number, but I can't find anything in the docs that would do the equivalent for column number at the same time.

The best idea I have is to create ~200 extra boolean columns in the table just to determine whether each cell is highlighted or not, hiding them, and using formatStyle(valueColumns = 201:400) to style the others. But that seems like massive overkill here. Any bright ideas?



Solution 1:[1]

library(tidyverse)
library(DT)
data <- rbind(c(1,2,3), c(4,5,6), c(7,8,9)) %>% as_tibble()
data
#> # A tibble: 3 x 3
#>      V1    V2    V3
#>   <dbl> <dbl> <dbl>
#> 1     1     2     3
#> 2     4     5     6
#> 3     7     8     9
data <-
  data %>%
  mutate(row_id = row_number()) %>%
  pivot_longer(-row_id) %>%
  group_by(row_id) %>%
  mutate(
    col_id = row_number(),
    value = value %>% as.character(),
    value = case_when(
      row_id == col_id ~ str_glue("<div style = 'color:red'> {value} </div>"),
      TRUE ~ value
    )
  ) %>%
  ungroup() %>%
  select(row_id, name, value) %>%
  pivot_wider() %>%
  select(-row_id)
data
#> # A tibble: 3 x 3
#>   V1                         V2                        V3                       
#>   <glue>                     <glue>                    <glue>                   
#> 1 <div style = 'color:red'>… 2                         3                        
#> 2 4                          <div style = 'color:red'… 6                        
#> 3 7                          8                         <div style = 'color:red'…

datatable(escape = FALSE, data)

enter image description here

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 danlooo