Search code examples
rflextable

Conditional Formatting of Flextable Correlation Table


I am looking for a way to conditional format a correlation matrix in flextable so that, given a specific value (e.g. .5), cells are highlighted that are above this value. I have looked at previous conditional formatting questions on SO, but have not been able to implement a solution. Here is my reprex, which ends up highlihting all cells:

my_data <- mtcars[, c(1,3,4,5,6,7)] #data
res <- cor(my_data) #initial correlation matrix

res[upper.tri(res)] <- NA # erase the upper triangle
diag(res) <- NA 

res %>%
  as.data.frame() %>%
  rownames_to_column("var") %>%
  flextable::flextable() %>%
  flextable::bg(i = rownames(res) > .5, j = 2:ncol(res), bg = "light blue")

Solution

  • This is a possible solution:

    library(flextable)
    library(magrittr)
    library(tibble)
    
    my_data <- mtcars[, c(1,3,4,5,6,7)] #data
    res <- cor(my_data) #initial correlation matrix
    
    res[upper.tri(res)] <- NA # erase the upper triangle
    diag(res) <- NA 
    
    res %>%
      as.data.frame() %>%
      rownames_to_column("var") %>%
      flextable::flextable() %>%
      flextable::bg(j = 2:ncol(res), 
                    bg = function(x){
                      out <- rep("transparent", length(x))
                      out[x < .5] <- "light blue"
                      out
                    })
    

    enter image description here