Search code examples
rdplyrr-markdownkable

Color cells in kable based on rowwise ranking of values


I have found how to format cells in a kable using cell_spec() and some fixed rules:

## coloring cell based on fixed value ranges
iris %>%
  select(-Species) %>%
  mutate_all(~cell_spec(.x, color = case_when(.x < 0 ~ "red",
                                              .x >= 0 ~ "black",
                                              is.na(.x) ~ "purple"))) %>%
  kable()

What I'd like to do though is color the text of each cell based on its ranking among the 4 values which appear in that row...

## what I want, to color cells based on row-wise value rank
iris %>%
  select(-Species) %>%
  rowwise() %>%
  mutate_all(~cell_spec(.x, color = ## largest value in row = green, 2nd is yellow, 3rd is orange, 4th is red
                          ) %>%
  kable()

Can I do this within my dplyr chain? Or if not how might I accomplish it?


Solution

  • You can create a function that will take a row of data, determine the rank (and handle ties), and then assign color of the cell using cell_spec based on the rank.

    You can use apply to row-wise use the custom function.

    library(tidyverse)
    library(kableExtra)
    library(knitr)
    
    df <- iris[, 1:4]
    
    my_fun <- function(x) {
      rnk <- rank(x, ties.method = "first")
      cell_spec(x, color = c("red", "orange", "yellow", "green")[rnk])
    }
    
    df <- t(apply(df, 1, my_fun))
    
    df %>%
      kable(escape = F) %>%
      kable_styling()
    

    Output

    table with colors determined by rank within row