Conditional Formatting w/ Multiple Rules

Hello. I'm using the openxlsx library to conditionally format fields. I am having trouble adding multiple conditions to the "rule" argument of the "conditionalformatting" function.

In the example below, I am trying to do the following:

  • If in the column "Fruit" the value = "Apple" AND if in the column "Tree" the value = "Green", then highlight the value in "Tree"

If there is a better way to conditionally format things in RStudio, I am open to that!

#Create Data Frame
library(openxlsx)
df <- data.frame(Fruit = c("Apple", "Orange", "Banana"),
                           Vegetables = c("Carrot", "Potato", "Corn"),
                 Tree = c("Green", "Green", "Brown"))

#Create Excel WorkBook
wb <-createWorkbook()
addWorksheet(wb, "Errors")
writeData(wb, "Errors", df) 

#Create Formatting Style
Yellow <- createStyle(fontColour= "#000000", bgFill = "#FFBF3F")

#Locate Errors
conditionalFormatting(wb, "Errors",
                      cols = 3,
                      rows = 1:3,
                      rule = '="Green" &  = "Apple"', #Where my code needs help
                      style = Yellow)

#Save
saveWorkbook(wb, "Highlighted Errors.xlsx", TRUE)

This topic was automatically closed 21 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.

Maybe this is what you're after:

#Create Data Frame
library(openxlsx)
df <- data.frame(Fruit = c("Apple", "Orange", "Banana"),
                 Vegetables = c("Carrot", "Potato", "Corn"),
                 Tree = c("Green", "Green", "Brown"))

#Create Excel WorkBook
wb <-createWorkbook()
addWorksheet(wb, "Errors")
writeData(wb, "Errors", df) 

#Create Formatting Style
Yellow <- createStyle(fontColour= "#000000", bgFill = "#FFBF3F")

#Locate Errors
conditionalFormatting(wb, "Errors",
                      cols = 3,
                      rows = 2:(nrow(df)+1),
                      type = "expression",
                      rule = 'AND($C2="Green",$A2="Apple")', 
                      style = Yellow)

openXL(wb)

image