如何使用gt包按行高亮每行中的最大值?
用gt包按行高亮每行最大值单元格(添加边框)
1. 生成宽格式数据集dat
先基于iris数据集,通过分组聚合、格式转换得到目标宽格式数据:
library(dplyr) library(tidyr) library(gt) # 按物种分组计算各指标均值,转换为宽格式:行=测量指标,列=物种,值=均值 dat <- iris %>% group_by(Species) %>% summarise(across(everything(), mean)) %>% pivot_longer(-Species, names_to = "Metric", values_to = "Value") %>% pivot_wider(names_from = Species, values_from = Value)
2. 按行高亮最大值单元格(添加边框)
核心是定位每行最大值所在的列,再给对应单元格添加边框样式,以下提供两种实用方法:
方法一:先标记最大值列再应用样式
先给每行标记最大值对应的物种列名,再逐行匹配样式:
# 标记每行最大值对应的物种列 dat_with_max <- dat %>% rowwise() %>% mutate(max_species = names(select(., -Metric))[which.max(c_across(-Metric))]) %>% ungroup() # 生成带高亮边框的gt表格 dat_with_max %>% gt() %>% tab_style( # 定义边框样式:红色2像素粗边框 style = cell_borders( sides = "all", color = "red", weight = px(2) ), # 定位目标单元格:每行的max_species列 locations = pmap( list(1:nrow(dat_with_max), dat_with_max$max_species), ~cells_body(columns = .y, rows = .x) ) )
方法二:直接计算定位单元格
无需额外标记列,直接逐行计算最大值位置:
dat %>% gt() %>% tab_style( style = cell_borders(sides = "all", color = "red", weight = px(2)), locations = { # 提取数值列,逐行找出最大值的列索引 num_cols <- select(dat, -Metric) max_pos <- apply(num_cols, 1, function(x) which(x == max(x))) # 转换为单元格位置并返回 pmap( list( rep(1:nrow(num_cols), sapply(max_pos, length)), names(num_cols)[unlist(max_pos)] ), ~cells_body(columns = .y, rows = .x) ) } )
补充说明
- 若同一行存在多个最大值(多列数值相同且为该行最大),两种方法都会给所有符合条件的单元格添加边框
- 可通过修改
cell_borders的参数调整边框颜色、粗细、显示方向
内容的提问来源于stack exchange,提问作者boshek
相关产品推荐
相关产品推荐

