kable 中的颜色单元格基于值的按行排序

Color cells in kable based on rowwise ranking of values

我找到了如何使用 cell_spec() 和一些固定规则来格式化 ka​​ble 中的单元格:

## coloring cell based on fixed value ranges
iris %>%
  select(-Species) %>%
  mutate_all(~cell_spec(.x, color = case_when(.x < 0 ~ "red",
                                              .x >= 0 ~ "black",
                                              is.na(.x) ~ "purple"))) %>%
  kable()

不过,我想做的是根据每个单元格在该行中出现的 4 个值中的排名,为每个单元格的文本着色...

## what I want, to color cells based on row-wise value rank
iris %>%
  select(-Species) %>%
  rowwise() %>%
  mutate_all(~cell_spec(.x, color = ## largest value in row = green, 2nd is yellow, 3rd is orange, 4th is red
                          ) %>%
  kable()

我可以在我的 dplyr 链中执行此操作吗?或者,如果不能,我该如何完成?

您可以创建一个函数来获取一行数据,确定排名(并处理关系),然后根据排名使用 cell_spec 分配单元格的颜色。

您可以使用 apply 按行使用自定义函数。

library(tidyverse)
library(kableExtra)
library(knitr)

df <- iris[, 1:4]

my_fun <- function(x) {
  rnk <- rank(x, ties.method = "first")
  cell_spec(x, color = c("red", "orange", "yellow", "green")[rnk])
}

df <- t(apply(df, 1, my_fun))

df %>%
  kable(escape = F) %>%
  kable_styling()

输出