Charlie
Charlie

Reputation: 198

Conditional format all flextable cells that match a string

I have a flextable with with the string 'Red' in some cells. I would like to highlight just these cells red.

I can check column by column as below, but I have a lot of columns in the actual table I want to use. Can this be done in one call to bg or another function, similar to the mutate_all function in dplyr?

data.frame(A = c("Red", "Other", "Other"), B = c("Green", "Orange", "Red"), stringsAsFactors = F) %>%
  as_tibble() %>%
  flextable() %>%
  bg(i = ~A=='Red', j = ~A, bg = 'red') %>%
  bg(i = ~B=='Red', j = ~B, bg = 'red')

This code achieves what I need, but specifies each column manually.

Upvotes: 3

Views: 1142

Answers (1)

cuttlefish44
cuttlefish44

Reputation: 6786

Could you be satisfied with classic method ?
If you don't have any reason to do it within single pipe-line, I guess here is safe way.

library(flextable); library(dplyr)

d <- data.frame(A = c("Red", "Other", "Other"), 
                B = c("Green", "Orange", "Red"), 
                stringsAsFactors = F) %>%
  as_tibble()

color_ind <- which(d == "Red", arr.ind = TRUE)
ft <- flextable(d)

for(i in 1:nrow(color_ind)) {
  ft <- ft %>% 
    bg(i = color_ind[i, 1], j = color_ind[i, 2], bg = 'red')
}

ft

Upvotes: 2

Related Questions