代码之家  ›  专栏  ›  技术社区  ›  J.Sabree

如何根据字符串更改flextable中的单元格文本颜色?

  •  1
  • J.Sabree  · 技术社区  · 10 月前

    在Flextable中,如果检测到“+”(绿色)或“-”(红色),我会尝试更改单元格中文本的颜色。这个 help guide 它非常清楚如何对数字数据执行此操作,但它没有显示如何基于检测特定字符串来执行此操作。我已经包含了示例数据和代码,但它给出了这个错误

    Error in rep(color, each = length(i)) : 
      attempt to replicate an object of type 'language'
    

    以下是示例代码:

    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
            )
      )
    

    我想要的输出是 age 列的文本和标题一样保持黑色。但是,我希望分数文本的颜色会根据分数是加还是减而变化(注意:并非我想改变颜色的所有单元格都有数字,所以如果可能的话,我不想用后门的方式检查数字是正是负)。

    2 回复  |  直到 10 月前
        1
  •  2
  •   jpsmith    10 月前

    您可以添加两个颜色语句,而不是 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")        
    

    enter image description here

        2
  •  2
  •   stefan    10 月前

    另一种选择是使用 function() \() 而不是a tidyverse style lambda函数显然不起作用,很可能不受支持:

    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 = \(x) {
          case_when(
            str_detect(x, "\\+") ~ "green",
            str_detect(x, "\\-") ~ "red",
            TRUE ~ "black"
          )
        }
      )
    

    enter image description here