Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Conditional format all flextable cells that match a string

Tags:

r

flextable

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.

like image 956
Charlie Avatar asked Jan 21 '26 02:01

Charlie


1 Answers

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
like image 155
cuttlefish44 Avatar answered Jan 22 '26 22:01

cuttlefish44



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!