Search code examples
rflextable

in flextable change all cells below threshold to bold face


I have the following sample data and would like to have all values below a certain value, e.g., 0, highlighted in bold. I can do this for individual columns, but not for all columns at once. I have the procedure for changing the font color, for example, but it does not seem so easy to convert the procedure to bold face.

Assuming that a table contains many columns, specifying each column seems very tedious. Also, looping through each column does not seem to be a suitable way to specify each column.

Sample data:

library(flextable)
library(tidyverse)

set.seed(0)
df <- data.frame(a = runif(10, -20, 20),
                 b = runif(10, -20, 20),
                 c = runif(10, -20, 20))

Example Code:

# bold face values below threshold for one column
ft <- df %>%
  flextable() %>%
  bold(., ~ a < 0, ~ a, bold = TRUE)

# change font color below threshold for all columns 
ft <- df %>%
  flextable() %>%
  color(color = function(x){
    out <- rep("black", length(x))
    out[x < 0] <- "red"
    out
  })

Solution

  • you have to put a boolean matrix with TRUE in cases to be bold

    like this

    x=as.matrix(df)
    out=matrix(FALSE,nrow = nrow(x),ncol=ncol(x))
    out[x < 0] <- TRUE
    ft=df%>%
      flextable()%>%
      bold(bold=out)