kable 中的条件格式 table

Conditional formatting in kable table

我遵循了来自 RStudio Community

的 Kable 条件格式脚本

我没有格式化列,而是在 table 中看到了 html 代码。

on_track_grades <- on_track_lanes %>%
  group_by(id_number) %>%
  mutate(grades = sum(mark %in% c("D", "F"))) %>%
  pivot_wider(names_from = department, values_from = mark) %>%
  mutate(percentage_present = 100 - as.numeric(percentage_absent)) %>%
  ungroup() %>%
  mutate(lanes = case_when(
    grades == 0 & cum_gpa > 3.5 ~ "Competitive",
    grades == 0 & cum_gpa >= 3.0 & cum_gpa <= 3.5 & percentage_present >= 80 ~ "Promising",
    grades <= 1 & cum_gpa >= 2.0 & cum_gpa <= 2.99 & percentage_present >= 70 ~ "Potential",
    grades <= 3 & cum_gpa >= 1.0 & cum_gpa <= 1.99 & percentage_present >= 50 ~ "Vulnerable",
    cum_gpa <= .99  ~ "Highly Vulnerable",
    TRUE ~ NA_character_
  )) %>% select(school_name, id_number, grades, cum_gpa, percentage_present, lanes) %>%
  drop_na() %>%
  mutate(lanes = cell_spec(lanes, background = case_when(
    lanes == "Competitive" ~  "#005488",
    lanes == "Promising" ~ "#715da6",
    lanes == "Potential" ~ "#c65da3",
    lanes == "Vulnerable" ~ "#ff6881",
    lanes == "Highly Vulnerable" ~ "#ff934f")))

on_track_grades %>%
  filter(school_name == params$school_name) %>%
  kbl(booktabs = TRUE,
      col.names = c("School", "Student ID", "# Ds & Fs", "GPA", "Present", "On-Track Lane"),
      align = c("l", "l", "r", "r", "r", "l"),
      linesep = "") %>%
  kable_paper(full_width = TRUE)

这是我得到的输出...

唯一缺少的是在 kbl 中指定 escape = FALSE。适用于 iris 数据的示例,因为您没有提供原始数据集“ontrack_lanes”

set.seed("12")
iris[sample(1:nrow(iris), 12),] %>%
  dplyr::select(Species, Sepal.Length, Sepal.Width) %>%
  mutate(Species = cell_spec(Species, background = case_when(
    Species == "setosa" ~  "#005488",
    Species == "versicolor" ~ "#715da6",
    Species == "virginica" ~ "#c65da3")))  %>%
  kbl(booktabs = TRUE,
      col.names = c("Species", "Sepal.Length", "Sepal.Width"),
      align = c("l", "r", "r"),
      linesep = "",
      escape = FALSE) %>%
  kable_paper(full_width = TRUE)