Search code examples
rtibbleflextable

Font color in flextable text


I have a tibble in R that has text (string) in the 3rd column that its cells has character and number.I want the number only to be colored but the text to remain black.

Is that possible to do that in R using flextable ?

For example I want the 85.5 to be red. 92.3 to be green and 78.9 purple.


library(tibble)

Score = c(85.5, 92.3, 78.9)

my_tibble = tibble(
  Name = c("Alice which is", "Bob is ", "Charlie aged"),
  Age = c(25, 30, 22),
  text = c(paste("has",Score[1]) , paste("and were",Score[2]), paste("scores",Score[3])))


# Print the tibble
my_tibble%>%
  flextable::flextable()%>%
  flextable::bg(i = 1:nrow(my_tibble),j = 1:ncol(my_tibble), 
                bg = "#EFEFEF", 
                part = "body")


Solution

  • You have to use mk_par() and color().

    library(flextable)
    library(tidyverse)
    
    Score <- c(85.5, 92.3, 78.9)
    
    my_tibble <- tibble(
      Name = c("Alice which is", "Bob is ", "Charlie aged"),
      Age = c(25, 30, 22),
      Score = Score,
      text = c(paste("has", Score[1]), paste("and were", Score[2]), paste("scores", Score[3]))
    )
    
    
    # with a function
    mycolors <- function(x) {
      indx <- seq_along(x)
      ifelse(
        indx < 2, "red",
        ifelse(indx < 90, "green", "purple")
      )
    }
    # or simpler 
    mycolors <- c("red", "green", "purple")
    
    
    # Print the tibble
    my_tibble |>
      flextable::flextable(col_keys = c("Name", "Age", "text")) |>
      flextable::mk_par(
        j = "text",
        value = as_paragraph(
          colorize("has ", "black"),# force it to black
          as_chunk(Score)# will use the default color
        )
      ) |>
      flextable::color(j = "text", color = mycolors, source = "Score") # change the default color
    

    enter image description here