使用 row_spec 的 Kable 条件着色
Kable conditional coloring using row_spec
我正在尝试使用 kable
根据条件为每行中的单元格着色。我看到了一些 column_spec 和 cell_spec 的例子,因为它仍然有点手动,因为我对按行进行条件着色很感兴趣。这是 column_spec 的示例,想知道是否可以使用 row_spec 或比 column_spec 或 cell_spec 更有效的类似方法来降低?
mtcars[1:8, 1:8] %>%
arrange(wt) %>%
kbl(booktabs = T, linesep = "") %>%
kable_paper(full_width = F) %>%
column_spec(6, color = "white", background = ifelse(mtcars[1:8,1:8]$drat > 3, "red", "green"))
但是,我感兴趣的条件格式是着色,比如 Mazda RX4 行的任何值 >10 然后是红色。这只是示例数据,因此上下文与此处无关。谢谢!
我们可以在管道进入 Kable
之前使用一些 dplyr
操作。
library(tidyverse)
library(knit)
library(kableExtra)
mtcars_kbl <- mtcars[1:8, 1:8]
mtcars_kbl$car = row.names(mtcars_kbl)
row.names(mtcars_kbl) <- NULL
mtcars_kbl %>% arrange(wt) %>%
relocate(car) %>%
mutate(
across(1:8,
~ cell_spec(.x,
color = ifelse(car == "Mazda RX4" & .x > 10, "white", "black"),
background = ifelse(car == "Mazda RX4" & .x > 10, "red", "white")
)
)
) %>%
kable(booktabs = T, linesep = "", format = "html", escape = F) %>%
kable_paper(full_width = F)
我正在尝试使用 kable
根据条件为每行中的单元格着色。我看到了一些 column_spec 和 cell_spec 的例子,因为它仍然有点手动,因为我对按行进行条件着色很感兴趣。这是 column_spec 的示例,想知道是否可以使用 row_spec 或比 column_spec 或 cell_spec 更有效的类似方法来降低?
mtcars[1:8, 1:8] %>%
arrange(wt) %>%
kbl(booktabs = T, linesep = "") %>%
kable_paper(full_width = F) %>%
column_spec(6, color = "white", background = ifelse(mtcars[1:8,1:8]$drat > 3, "red", "green"))
但是,我感兴趣的条件格式是着色,比如 Mazda RX4 行的任何值 >10 然后是红色。这只是示例数据,因此上下文与此处无关。谢谢!
我们可以在管道进入 Kable
之前使用一些 dplyr
操作。
library(tidyverse)
library(knit)
library(kableExtra)
mtcars_kbl <- mtcars[1:8, 1:8]
mtcars_kbl$car = row.names(mtcars_kbl)
row.names(mtcars_kbl) <- NULL
mtcars_kbl %>% arrange(wt) %>%
relocate(car) %>%
mutate(
across(1:8,
~ cell_spec(.x,
color = ifelse(car == "Mazda RX4" & .x > 10, "white", "black"),
background = ifelse(car == "Mazda RX4" & .x > 10, "red", "white")
)
)
) %>%
kable(booktabs = T, linesep = "", format = "html", escape = F) %>%
kable_paper(full_width = F)