如何用R的gt库实现HTML RMarkdown表格条件格式与列宽调整
使用gt库实现数据框条件格式化与第一列宽调整
以下是满足需求的完整实现代码,包含对初始思路的优化:
library(gt) library(dplyr) # 定义条件填充规则函数 cell_style <- function(x) { case_when( x >= 2 & x < 3 ~ cell_fill(color = "red"), x >= 3 & x < 4 ~ cell_fill(color = "orange"), x >= 4 & x <= 5 ~ cell_fill(color = "green"), TRUE ~ NULL # 不匹配规则时保留默认样式 ) } # 用户提供的数据框 df <- structure(list(projects = c("Restaurant, Pizzeria and Pasta House Works for New York", "London Project - New Restaurant Project", "Athens - Beautiful Lands for Aigaleo City Project", "Berlin City - Exhibition near the airport with restaurants", "Pizzeria Buenos Aires New italian restaurant - pasta, tartufo and vino", "area mean value", "total mean value"), happiness.and.joyfullness = c(3.5,4, 3, 3.2, 4, 5, 3), joy.for.children = c(3, 5, 3, 4, 5,4, 4), area = c(3, 5, 3, 3, 3, 4, 4), damages.from.environment = c(2,4, 2, 3, 3, 5, 5), approach = c(3, 1, 5,3, 5, 5, 4), expensive = c(3, 5, 3, 4, 5, 5, 5), safety.comes.first = c(5,5, 5, 5, 5, 5, 4), hungry = c(3, 5, 2, 4, 5,5, 5)), row.names = c(NA, -7L), class = c("tbl_df", "tbl","data.frame")) # 生成并格式化表格 gt_table <- df %>% gt() %>% # 设置第一列宽度,适配长文本(可根据实际调整px值) cols_width(projects ~ px(350)) %>% # 第一列左对齐,文本自动换行 cols_align(projects = "left") %>% # 表格占满容器宽度,优化显示 tab_options(table.width = "100%") %>% # 对除第一列外的所有单元格应用条件填充 tab_style( style = cell_style(.$`_data`[, -1]), locations = cells_body(columns = -projects) ) # 输出表格 gt_table
关键细节说明
- 函数优化:将原函数中
TRUE分支的cell_text(color = "black")改为NULL,避免覆盖默认文本样式,值小于2的单元格(如approach列的1)会保持原有样式。 - 列宽调整:用
cols_width指定projects列的固定像素宽度,可根据文本长度灵活调整px()中的数值;搭配cols_align和tab_options让长文本自动换行,提升可读性。 - 条件格式应用:通过
tab_style结合自定义函数,columns = -projects精准指定作用范围为除第一列外的所有数据单元格。
内容的提问来源于stack exchange,提问作者Homer Jay Simpson
相关产品推荐
相关产品推荐

