In Flextable, I'm trying to change the color of the text in a cell if it detects a "+" (green) or "-" (red). The help guide is really clear on how to do this for numeric data, but it doesn't show how to do it based on detecting specific character strings. I've included sample data and code, but it gives this error
Error in rep(color, each = length(i)) :
attempt to replicate an object of type 'language'
Here's the sample code:
library(flextable)
library(tidyverse)
sample_data <- tibble(
age = c(20, 40, 30, 50),
score = c("+5pp", "-4pp", "+7pp", "-10pp")
)
sample_data %>%
flextable() %>%
color(part = "body",
color = ~ case_when(
str_detect(., "+") ~ "green",
str_detect(., "-") ~ "red",
TRUE ~ "black" # Default color
)
)
My desired output is the the age
column's text stays black as does the header. However, I want the score text color to change depending if the score has a plus or minus (note: not all my cells that I want to change color have numbers, so I don't want a backdoor way of check if the number is positive/negative if possible).
You can add two color statements instead of case_when
:
sample_data %>%
flextable() %>%
color(i = ~ grepl("\\+", score), j = "score", color = "green") %>%
color(i = ~ grepl("-", score), j = "score", color = "red")
# or using `stringr`:
sample_data %>%
flextable() %>%
color(i = ~ stringr::str_detect(score, "\\+"), j = "score", color = "green") %>%
color(i = ~ stringr::str_detect(score, "-"), j = "score", color = "red")