读入单个 xlsx 文件,执行条件格式化并导出为 R 中的多个 xlsx 文件

Read in single xlsx file, perform conditional formatting and export as as multiple xlsx files in R

初始数据集:

df = data.frame(Division=c("ASIA","ASIA","ASIA","ASIA","ASIA","EUROPE","EUROPE","EUROPE"),
 Country=c("India","China","Japan","Nepal","Laos","France","Italy","Norway"),
 improvement=c(1,3,7,5,9,8,2,7))

我可以将这个 xlsx 文件读入 R,我希望能够执行以下操作:

  1. 突出显示改进值小于 5 的任何行。
  2. 根据部门名称将数据导出到不同的 xlsx 文件中。例如,导出的第一个 xlsx 文件将只有 df 中数据的前 5 行,突出显示印度和中国,而导出的另一个文件将包含来自欧洲的 3 行,突出显示意大利。

任何指点将不胜感激!!

您可以先使用 openxlsx 创建一个函数来创建工作簿。
然后,您可以 split 按部门划分数据集,并使用 map 调用部门的工作簿创建:

library(openxlsx) 
library(purrr)
library(dplyr)

threshold <- 6

create.workbook <- function(df,threshold) {
 wb <- createWorkbook() 
 highlight.Style <- createStyle(fontColour = "red", fgFill = "yellow")
 addWorksheet(wb, "data")
 writeData(wb, sheet = "data", x = df)
 highlight.rows <- which(df$improvement < threshold)+1
 addStyle(wb, "data", cols = 1:ncol(df), rows = highlight.rows,
          style = highlight.Style, gridExpand = TRUE)
 
 wb.name <- df$Division[1]
 saveWorkbook(wb,paste0(wb.name,'.xlsx'),overwrite = T)
}

df %>% split(.$Division) %>% map(~create.workbook(.x,threshold))

$ASIA
[1] 1

$EUROPE
[1] 1