xal*_*.ey 4 r dplyr tidyverse gt
我正在尝试使用条件格式化我的 gt 表,但有点停滞不前。我发现的大多数示例都是基于列标题的格式。
这是示例表的代码,其中第一列名为“row”,值为 1-6。我如何让 gt 表仅向第 1 行的值 > 3.0 添加颜色?这是我的第一个问题,如果我搞砸了,请道歉!

library(tidyverse)
library(gt)
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="_"
)
Run Code Online (Sandbox Code Playgroud)
我们可以添加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
)
)
Run Code Online (Sandbox Code Playgroud)
-输出
根据评论,如果我们需要为每一列使用一个条件,那么我们可以使用一个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
)
)
}
Run Code Online (Sandbox Code Playgroud)
-输出