通过 Rmarkdown 具有条件着色的表格以 PDF 形式渲染

问题描述 投票:0回答:1

我在 R 中有一个表,有 4 列。第一列名称为 John Helen 和 George。第二列名称为 Pizza,值为 0.7、0.5、0.33.3 第三列名称为意大利面,值为 0.4、0.7、0.2。第四列名称 sweet,值为 0.9、0.3、0.2。

df <- data.frame(
  Name = c("John", "Helen", "George"),
  Pizza = c(0.7, 0.5, 0.33),
  Pasta = c(0.4, 0.7, 0.2),
  Sweet = c(0.9, 0.3, 0.2)
)

print(df)

现在我想根据 3)标准为每个单元格着色:如果值 >=0.7,则将其着色为绿色,如果单元格值为 <= 0.3 and >= 0.15 黄色,否则为白色。

library(formattable)


rules <- formatter(
  "span",
  style = x ~ style(
    color = ifelse(x >= 0.7, "green", ifelse(x <= 0.3 & x >= 0.15, "yellow", "white"))
  )
)


formattable_df <- as.data.frame(lapply(df, function(x) as.character(rules(x))))


print(formattable_df)

现在我想将它们全部放入 rmarkdown 文件中以渲染 PDF Latex 样式(最好是乳胶表),但要在生成的 PDF 文件中保留条件着色。我该怎么做?

r colors r-markdown
1个回答
2
投票

我喜欢通过创建一个函数来实现此目的,该函数使用

kableExtra::cell_spec()
:

适当地格式化数据
set_background <- function(x, color = "white", format = "latex") {
    kableExtra::cell_spec(x, format = format, background = color)
}

然后您可以使用

dplyr::across()
:

将其应用到数据的相关列
library(dplyr)
df |>
    mutate(
        across(Pizza:Sweet, \(x)
            case_when(
                x > 0.7 ~ set_background(x, "green"),
                x >= 0.15 & x <= 0.3 ~ set_background(x, "yellow"),
                TRUE ~ set_background(x)
            )
        )
    ) |>
    kableExtra::kbl(format="latex", booktabs=TRUE, escape=FALSE)

确保您的 rmarkdown yaml 标头包含适当的包:

---
output: pdf_document
header-includes:
  - \usepackage{booktabs}
  - \usepackage[table]{xcolor}
---

输出:

© www.soinside.com 2019 - 2024. All rights reserved.