使用 gt() 在多列中有条件地更改字体颜色

change font color conditionally in multiple columns using gt()

这个问题与这个问题相关:How can I color the same value in the same color in the entire gt table in R?

基本上,OP 要求有条件地更改 gt 对象中的字体颜色:

if value == 4 -> 蓝色字体 如果值 == 0 -> 字体红色

原来并没有想象中那么容易。我设法更改了特定列中的颜色,例如:

library(gt)
library(dplyr)

mtcars %>% 
  gt() %>% 
  tab_style(
    style = cell_text(color = "red", weight = "bold"),
    locations = cells_body(
      columns = am,
      rows = am == 0
    )
  ) %>% 
  tab_style(
    style = cell_text(color = "blue", weight = "bold"),
    locations = cells_body(
      columns = cyl,
      rows = cyl == 4
    )
  )

给出:

我的问题: 我如何修改我的代码以将这些条件应用于所有列!

例如所有 0 都是红色,所有 4 都是蓝色!

如果我们只想在特定列上执行此操作,请创建一个名称向量 ('nm1') 并仅遍历这些列,在循环内,获取满足 [=12 中条件的索引=]

library(dplyr)
library(gt)
 tbl1 <- mtcars %>% 
     gt()
 nm1 <- c("cyl", "vs", "am", "gear", "carb")
 for(i in seq_along(nm1)) {
      
      tbl1 <- tbl1 %>%
        tab_style(
          style = list(
            cell_text(color = "red", weight = "bold")
            
          ),
          locations = cells_body(
            columns = nm1[i],
            
            rows = tbl1$`_data`[[nm1[i]]] == 0 
          )
        ) %>%
        
        tab_style(
          style = list(
            cell_text(color = "blue", weight = "bold")
            
          ),
          locations = cells_body(
            columns = nm1[i],
            
            rows = tbl1$`_data`[[nm1[i]]] == 4 
          )
        ) 
        
    }

-输出


另一种选择是使用 across 在每一列中创建 gt 对象,存储 as_raw_html,然后使用 fmt_markdown

out <-  mtcars %>%
    summarise(across(everything(),  ~ 
                          setNames(tibble(.x), cur_column()) %>%
                                  gt() %>%
                                 tab_style(
                                   style = cell_text(color = "red", weight = "bold"),
                                   locations = cells_body(
                                     columns = cur_column(),
                                     rows = .x == 0
                                   )
                                 ) %>% 
                                 tab_style(
                                   style = cell_text(color = "blue", weight = "bold"),
                                   locations = cells_body(
                                     columns = cur_column(),
                                     rows = .x == 4
                                   )
                                 ) %>%
                       as_raw_html()
                                          
    ))
 
out1 <- out %>%
     gt() %>%
   fmt_markdown(columns = everything())
out1