在 R 中使用 openxlsx 包的条件格式不起作用

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

我有以下代码,我希望列

Score
根据列
max
的值有条件地格式化。如果得分为 8 且最大值为 8,则为绿色。如果得分为 4 且最大值为 8,则为黄色。如果分数为 4 且最大值为 4,则为绿色。如果得分为 2 且最大值为 4,则为黄色。如果分数为 0,则为红色。但是,以下似乎不起作用(仅测试绿色)。

library(tibble)
library(openxlsx)

data <- tribble(
  ~Week, ~Facility, ~Indicator, ~`Indicator Value`, ~`Yellow Gap`, ~`Green Gap`, ~Score, ~max,
  8, "Mngeta Health Center", "3MMD Coverage", 0.96, -13, 10, 4, 8,
  8, "Mngeta Health Center", "12 Month Retention", 0.96, 35, 50, 2, 4,
  8, "Mngeta Health Center", "Appointment Adherence", 0.97, 11, 24, 0, 8,
  8, "Mngeta Health Center", "EID 12 Months", 1, 0, 0, 8, 8,
  8, "Mngeta Health Center", "Early Retention", 1, 0, 0, 8, 8,
  8, "Mngeta Health Center", "Recent Retention", 1.04, -19, -5, 8, 8,
  8, "Mngeta Health Center", "6MMD Coverage", 0.98, -29, -9, 8, 8,
  8, "Mngeta Health Center", "IPT Coverage", 0.99, -15, -1, 4, 4,
  8, "Mngeta Health Center", "EID 2 Months", 1, 0, 0, 8, 8,
  8, "Mngeta Health Center", "Viral Load Coverage", 0.95, -67, -2, 8, 8
)

# Convert Score column to numeric
data$Score <- as.numeric(data$Score)

wb <- createWorkbook()

# Add a new worksheet
addWorksheet(wb, "Formatted Data")

# Write the data to the worksheet
writeData(wb, "Formatted Data", data)

# Create a style object for green color
green_style <- createStyle(bgFill = "green")

conditionalFormatting(wb, sheet = "Formatted Data",
                      cols = which(colnames(data) == "Score"), rows = 2:nrow(data),
                      rule = "Score==8 & max==8", style = green_style)

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

创建于 2023-02-25 由 reprex 包 (v2.0.1)

r conditional-formatting openxlsx
© www.soinside.com 2019 - 2024. All rights reserved.