我有以下表格:
我想只在"my_sum"中的单元格中使用黄色高亮。值大于0时的行。如何对分组数据执行此操作?我假设某种类型的函数来识别放入tab_style的数据中的分组?
这是我的代表
library(gt)
library(tidyverse)
tibble(cars = c("honda", "honda",
"ford", "ford"),
mpg = c(24, 22,
NA, NA),
wt = c(NA, NA,
3432, 4234)
) %>%
group_by(cars) %>%
gt() %>%
fmt_missing(columns = everything(),
missing_text = "") %>%
summary_rows(
groups = TRUE,
columns = c(mpg:wt),
fns = list("my_sum" = ~sum(., na.rm = TRUE)),
missing_text = "",
formatter = fmt_number,
decimals = 0
) %>%
grand_summary_rows(
columns = c(mpg:wt),
fns = list("my_big_sum" = ~sum(., na.rm = TRUE)),
missing_text = "",
formatter = fmt_number,
decimals = 0
) %>%
tab_options(
row_group.font.weight = "bold"
) %>%
tab_style(
style = list(
cell_fill(color = "#d4ebf2")
),
locations = cells_grand_summary(
columns = c("mpg", "wt")
)
) %>%
tab_style(
style = list(
cell_fill(color = "#FFFFE0")
),
locations = cells_summary(
columns = c("mpg", "wt")
)
)
这个答案有点粗糙和手动,但它有效。首先将表保存为对象。然后你可以直接访问表格样式并手动修改它们。
library(gt)
library(tidyverse)
tibble(cars = c("honda", "honda",
"ford", "ford"),
mpg = c(24, 22,
NA, NA),
wt = c(NA, NA,
3432, 4234)
) %>%
group_by(cars) %>%
gt() %>%
fmt_missing(columns = everything(),
missing_text = "") %>%
summary_rows(
groups = TRUE,
columns = c(mpg:wt),
fns = list("my_sum" = ~sum(., na.rm = TRUE)),
missing_text = "",
formatter = fmt_number,
decimals = 0 ) %>%
grand_summary_rows(
columns = c(mpg:wt),
fns = list("my_big_sum" = ~sum(., na.rm = TRUE)),
missing_text = "",
formatter = fmt_number,
decimals = 0
) %>%
tab_options(
row_group.font.weight = "bold"
) %>%
tab_style(
style = list(
cell_fill(color = "#d4ebf2")
),
locations = cells_grand_summary(
columns = c("mpg", "wt")
)
) %>%
tab_style(
style = list(
cell_fill(color = "#FFFFE0")
),
locations = cells_summary(
columns = c("mpg", "wt"),
rows = "my_sum" )
) -> t1
x1 <- t1$`_styles`$styles[4]
x2 <- t1$`_styles`$styles[3]
x2[[1]]$cell_fill$color <- "#FFFFFF"
t1$`_styles`$styles[3] <- x1
t1$`_styles`$styles[4] <- x2
t1$`_styles`$styles[6] <- x1
t1$`_styles`$styles[5] <- x2