我有一个 gt 表格,需要多列边框。我可以轻松更改目标行和/或列的颜色,正如您在本示例中看到的,将“无花果”的边框更改为紫色。
library(dplyr)
exibble %>%
gt() %>%
cols_align(align = "center",
columns = c("char")) %>%
tab_style(
style = list(
cell_borders(
sides = c("all"),
color = c("purple"),
weight = px(3)
)
),
locations = list(
cells_body(
columns = "char",
rows = char == "fig"
)
)
)
但是,当我尝试从包含颜色的另一列一次更改多种颜色时,出现错误:
exibble %>%
mutate(col = case_when(char == "fig" ~ "purple",
char == "banana" ~ "yellow",
TRUE ~ "white")) %>%
gt() %>%
cols_align(align = "center",
columns = c("char")) %>%
tab_style(
style = list(
cell_borders(
sides = c("all"),
color = from_column(col),
weight = px(3)
)
),
locations = list(
cells_body(
columns = "char",
rows = !is.na(col)
)
)
)
Error in `cell_borders()`:
! `color` must have a length one, not 3.
如何使整个列反映预期的边框颜色(白色、紫色或黄色),而不必一一定位这些单元格值?
使用
cell_fill
功能可设置多种单元格颜色。
exibble %>%
mutate(col = case_when(char == "fig" ~ "purple",
char == "banana" ~ "yellow",
TRUE ~ "white")) %>%
gt() %>%
cols_align(align = "center",
columns = c("char")) %>%
tab_style(
style = cell_fill(color = from_column(column = "col")),
locations = cells_body(columns = col)
)
)