R-Markdown(四开本)中 table 的条件单元格格式问题

Problems with conditional cell formatting for table in R-Markdown (Quarto)

我正在为 bean 聚合创建一个 R-Markdown (Quarto) 文档。我在文档中有一个 table,我希望其中一列(进度)根据单元格值进行条件突出显示(如果小于 30,则为红色,如果大于 70,则为绿色,否则为橙色)。

R-Markdown 代码如下(我不知道如何reprex R-Markdown 代码):

---
title: "delete later"
author: "Tumaini"
format: pdf
editor: visual
---

## Aggregated beans stock

The intention is that the **progress column** is color-coded depending on the value of the cell. It should be **red** if less than 30%, orange between 30% and 70% and green if above 70%

```{r, include=FALSE}
library(tidyverse)

beans_stock = tibble::tribble(
   ~`Data Entry`, ~District,           ~Ward,             ~AMCOS, ~`Bean Stock (MT)`, ~`Target (MT)`, ~Progress,
  "2022-03-30",  "Kasulu",    "Nyakitonto",       "Nyakitonto",               94.3,           330L,       29L,
  "2022-03-29",  "Kasulu",     "Nyachenda",          "Twikome",               63.3,           202L,       31L,
  "2022-03-29", "Kibondo",      "Kitahana",         "Kitahana",               48.3,            88L,       55L,
  "2022-03-29",  "Kasulu",     "Nyachenda",         "Motomoto",               44.8,           152L,       29L,
  "2022-03-29",  "Kasulu",      "Kitagata",          "Ubhumwe",               37.6,           123L,       31L,
  "2022-03-30", "Kakonko",    "Kiziguzigu",       "Kiziguzigu",               34.4,           410L,        8L,
  "2022-03-29", "Kibondo", "Kibondo-Mjini",    "Kibondo-Mjini",               17.3,           140L,       12L,
  "2022-03-26", "Kibondo",      "Kitahana",             "Ruti",                6.9,           210L,        3L,
  "2022-03-29", "Kibondo",      "Bunyambo", "Kibondo-Bunyambo",                  4,           140L,        3L,
  "2022-03-17", "Kibondo",      "Kitahana",             "Ruti",                0.6,           210L,        0L
  )



```

```{r}
beans_stock %>% 
  mutate(
    Progress = kableExtra::cell_spec(
      Progress, background = ifelse(Progress > 70,"green",
                                    ifelse(Progress < 30,"red","orange")))
  ) %>% 
  kableExtra::kable(escape = FALSE,format = "latex") %>% 
  kableExtra::kable_styling("striped", full_width = T)

```

但是这不起作用,任何人都可以指出我可能做错了什么吗?目的是呈现为 PDF。

如果您将 background 更改为 color 作为 cell_spec() 中的参数,您的代码将按预期工作。

如果你想要彩色背景,你需要删除最后一行代码kableExtra::kable_styling("striped", full_width = T)

如果你想要全宽,你需要在kable_styling中调整乳胶选项:

beans_stock %>% 
  mutate(
    Progress = kableExtra::cell_spec(
      Progress, background = ifelse(Progress > 70,"green",
                                    ifelse(Progress < 30,"red","orange")))
  ) %>% 
  kableExtra::kable(escape = FALSE,format = "latex", booktabs = T) %>% 
  kableExtra::kable_styling(latex_options="scale_down")