我们可以添加tab_style 和cell_fill,并指定locations 和columns 和rows
library(dplyr)
library(tidyr)
library(gt)
library(stringr)
iris %>%
group_by(Species) %>%
slice_max(Sepal.Length, n=5) %>%
group_by(Species) %>%
mutate(row=row_number()) %>%
pivot_longer(-c(Species, row)) %>%
mutate(Species = str_to_title(Species),
name = gsub("\\.", " ", name)) %>%
pivot_wider(names_from=c(Species, name), values_from=value)%>%
gt() %>%
tab_spanner_delim(
delim="_"
) %>%
tab_style(
style = list(
cell_fill(color = "lightgreen")
),
locations = cells_body(
columns = c(`Setosa_Sepal Length`, `Setosa_Sepal Width`,
`Versicolor_Sepal Length`, `Versicolor_Sepal Width`, `Versicolor_Petal Length`,
`Virginica_Sepal Length`,`Virginica_Sepal Width`, `Virginica_Petal Length`),
rows = 1
)
)
-输出
更新
基于 cmets,如果我们需要为每一列使用条件,那么我们可以使用 for 循环来循环列名并添加条件层并更新原始 gt 对象( 'tbl1')
tbl1 <- iris %>%
group_by(Species) %>%
slice_max(Sepal.Length, n=5) %>%
group_by(Species) %>%
mutate(row=row_number()) %>%
pivot_longer(-c(Species, row)) %>%
mutate(Species = str_to_title(Species),
name = gsub("\\.", " ", name)) %>%
pivot_wider(names_from=c(Species, name), values_from=value)%>%
gt() %>%
tab_spanner_delim(
delim="_"
)
nm1 <- names(tbl1$`_data`)[-1]
for(i in seq_along(nm1)) {
tbl1 <- tbl1 %>%
tab_style(
style = list(
cell_fill(color = "lightgreen")
),
locations = cells_body(
columns = nm1[i],
rows = seq_along(tbl1$`_data`[[nm1[i]]]) == 1 &
tbl1$`_data`[[nm1[i]]] > 3
)
)
}
-输出