在 R 中格式化 xlsx:根据具有列名称的值突出显示列中的单元格

问题描述 投票:0回答:1

我使用 R 进行分析,列出每年和物种的一堆计数;列中的年份和行中的物种。我下面有一个小的虚拟数据集。数据集的最后一列 (year_highlighted) 显示该物种被正式列出的年份。我想突出显示与“year_highlighted”中提到的列(年份)相对应的单元格。

我看过几篇关于条件格式的帖子(如this),但这些帖子使用值本身来格式化单元格。其他帖子已经有十多年的历史了,我认为现在有更好的方法(比如this)。对我来说,我有对需要格式化单元格的列的引用。我想在 R 中完成这一切,这样我就不必在 Excel 中手动突出显示单元格。

这是一个小示例数据集

species_year <- structure(list(fruit = c("apple", "apricot", "avocado"), `2022` = c(9.676, 
9.285, 9.557), `2023` = c(10.891, 
10.097, 9.359), `2024` = c(10.031, 
8.983, 11.389), year_highlight = c(2023, 
2024, 2023)), row.names = c(NA, -3L), class = c("tbl_df", "tbl", 
"data.frame"))

这是我的预期输出:

r formatting xlsx highlight conditional-formatting
1个回答
0
投票

您可以使用“openxlsx”来完成此操作。

有一个更新的软件包“openxlsx2”可能提供另一种方法,但我还没有从旧的

openxlsx
中转移。

library(openxlsx)

# generate a vectors for column and row coorinates for cells which need background colour
# nothing sophisticated about this approach due to the example data

row_vec <- seq_len(nrow(species_year)) + 1
col_vec <- species_year$year_highlight - 2020




wb <- createWorkbook()
addWorksheet(wb, sheetName = "fruits")

writeData(wb, sheet = 1, x = species_year)

# create style for background colour
s1 <- createStyle(fgFill = "gold")

addStyle(wb, 
         sheet = 1,
         style = s1, 
         rows =  row_vec, 
         cols = col_vec)


saveWorkbook(wb, "species_year.xlsx", overwrite = TRUE)

结果是:

创建于 2024-04-18,使用 reprex v2.0.2

© www.soinside.com 2019 - 2024. All rights reserved.