如何使用 gt() 为每个其他类别着色?
How do I colour every other category with gt()?
library(gt)
library(dplyr)
data <- 1:150 %>% sample(10) %>% iris[.,]
data
Sepal.Length Sepal.Width Petal.Length Petal.Width Species
68 5.8 2.7 4.1 1.0 versicolor
102 5.8 2.7 5.1 1.9 virginica
61 5.0 2.0 3.5 1.0 versicolor
81 5.5 2.4 3.8 1.1 versicolor
49 5.3 3.7 1.5 0.2 setosa
4 4.6 3.1 1.5 0.2 setosa
117 6.5 3.0 5.5 1.8 virginica
26 5.0 3.0 1.6 0.2 setosa
142 6.9 3.1 5.1 2.3 virginica
91 5.5 2.6 4.4 1.2 versicolor
我想达到的效果是这样的:
data %>% arrange(Species) %>% gt() %>%
tab_style(
style = cell_fill(color = '#F0FDEC'),
locations = cells_body(
rows = Species == 'setosa')) %>%
tab_style(
style = cell_fill(color = '#F0FDEC'),
locations = cells_body(
rows = Species == 'virginica'))
我不想手动指定应该为哪些物种着色,以便代码可以扩展。
提前致谢!
您可以转换为 numeric
(如果尚未转换为 factor
,则可以转换为 factor
)并为每个不均匀的组 ID 设置 TRUE
:
data %>%
arrange(Species) %>%
gt() %>%
tab_style(
style = cell_fill(color = '#F0FDEC'),
locations = cells_body(
rows = as.numeric(Species) %% 2 == 1))
library(gt)
library(dplyr)
data <- 1:150 %>% sample(10) %>% iris[.,]
data
Sepal.Length Sepal.Width Petal.Length Petal.Width Species
68 5.8 2.7 4.1 1.0 versicolor
102 5.8 2.7 5.1 1.9 virginica
61 5.0 2.0 3.5 1.0 versicolor
81 5.5 2.4 3.8 1.1 versicolor
49 5.3 3.7 1.5 0.2 setosa
4 4.6 3.1 1.5 0.2 setosa
117 6.5 3.0 5.5 1.8 virginica
26 5.0 3.0 1.6 0.2 setosa
142 6.9 3.1 5.1 2.3 virginica
91 5.5 2.6 4.4 1.2 versicolor
我想达到的效果是这样的:
data %>% arrange(Species) %>% gt() %>%
tab_style(
style = cell_fill(color = '#F0FDEC'),
locations = cells_body(
rows = Species == 'setosa')) %>%
tab_style(
style = cell_fill(color = '#F0FDEC'),
locations = cells_body(
rows = Species == 'virginica'))
我不想手动指定应该为哪些物种着色,以便代码可以扩展。
提前致谢!
您可以转换为 numeric
(如果尚未转换为 factor
,则可以转换为 factor
)并为每个不均匀的组 ID 设置 TRUE
:
data %>%
arrange(Species) %>%
gt() %>%
tab_style(
style = cell_fill(color = '#F0FDEC'),
locations = cells_body(
rows = as.numeric(Species) %% 2 == 1))