如何使用 `openxlsx::conditionalFormatting` 为代码值着色?

How to color code values with `openxlsx::conditionalFormatting`?

如何在列索引列表上使用 openxlsx::conditionalFormatting,不一定按顺序排列?在文档中,?conditionalFormatting,所有示例都用 : 填充 cols 参数,例如 cols = 1:5 意思是 1,2,3,4,5;但是,我希望根据索引是否在列表中对列进行颜色编码。列索引不一定像 1:5 这样的数字顺序。它可能是 1,2,4,6,8 或类似的东西。

举个例子:

library(tidyverse)
# install.packages("openxlsx")
library(openxlsx)
library(writexl)
library(glue)

data_format <- data.frame(vals = c(5,6,2,12,5,12,5,4.5,12,13,3,15,17,30,7,19),
                      vals1 = c(2,6,2,12,13,12,5,4.5,12,13,3,15,19,30,7,9),
                      vals2 = c(2,7,2,7,13,12,5,4.5,12,1,3,15,20,30,7,6),
                      vals3 = c(1,20,2,8,12,1,1,9,4.2,16,11,3,14,10,28,5),
                      vals4 = c(5,13,2,12,13,12,1,4.5,12,10,3,15,20,29,7,9),
                      vals5 = c(5,15,2,10,18,11,3,4.5,12,13,2,15,86,90,9,11),
                      thresh1 = c(4,11,9,13.5,12,12,6,4.8,10,14,3,17,22,80,8,13),
                      thresh2 = c(6,12,1,13,16,11,5,3,16,12,1,13,19,20,6,10))

data_format <-
  data_format %>%
  relocate(thresh1, .before=vals)

data_format <-
  data_format %>%
  relocate(thresh2, .after=thresh1)

wb <- createWorkbook()


addWorksheet(wb, "data_format")

writeData(wb, "data_format",data_format)

Colpink1 <- c(4,5,6,8) # I would expect these columns to be pink when they are less than column A

Colpurple2 <- c(3,7) # I would expect these columns to be purple when they are less than column B

pinkStyle <- createStyle(fontColour = "#FA977C")
purpleStyle <- createStyle(fontColour = "#9B7CFA")

conditionalFormatting(wb, "data_format",
                      cols = Colpink1,
                      rows = 2:nrow(data_format), rule = "<$A2", style = pinkStyle
)

conditionalFormatting(wb, "data_format",
                      cols = Colpurple2,
                      rows = 2:nrow(data_format), rule = "<$B2", style = purpleStyle
)





filepath <-
  glue("PATH/format_coloring.xlsx") 

saveWorkbook(wb, file = filepath)

C 列如预期的那样是紫色的,但 G 列具有粉红色和紫色值。我希望 G 只是根据紫色进行颜色编码。其他列混合了粉红色和紫色,我希望是粉红色。有没有人知道如何根据不按顺序的索引有条件地格式化?

如果有人有想法,我们将不胜感激。

cols 参数看起来需要范围,即使您指定 c(4,5,6,8) 被解释为第 4-8 列(包括第 7 列)。您可以循环遍历 Colpink1 和 Colpurple2,应用条件格式

wb <- createWorkbook()



addWorksheet(wb, "data_format")

writeData(wb, "data_format",data_format)

Colpink1 <- c(4,5,6,8) 

Colpurple2 <- c("C","G") #just testing that column letters worked too

pinkStyle <- createStyle(fontColour = "#FA977C")
purpleStyle <- createStyle(fontColour = "#9B7CFA")

for(i in Colpink1){
conditionalFormatting(wb, "data_format",
                      cols = i,
                      rows = 2:nrow(data_format), rule = "<$A2", style = pinkStyle)
}

for(i in Colpurple2){
conditionalFormatting(wb, "data_format",
                      cols = i,
                      rows = 2:nrow(data_format), rule = "<$B2", style = purpleStyle)
}

openXL(wb)