I am writing this r code that selects the top 3 values (positive and negative) in one column B based on values of another column C (1 or 0). if it is column C is 1, then the value in column B is picked up else dropped and highlights the row in light green for positive values and light blue for negative values. Everything works well but the color formatting. The output shows all the top values(negative & positive) rows in dark.
1st table is data & 2nd table output.
my code:
# Sort to get top 3 positive and negative values in the 'diff' column excluding row 'O'
data_filtered <- data[!(rownames(data) == "14"), ]
sorted_data <- data_filtered[order(data_filtered$Diff, decreasing = TRUE), ]
top_positive <- head(sorted_data, 3)
sorted_data <- data_filtered[order(data_filtered$Diff, decreasing = FALSE), ]
top_negative <- head(sorted_data, 3)
# Combine and filter rows where B == 1
top_values <- rbind(top_positive, top_negative)
top_values <- top_values[top_values$B == 1, ]
wb <- createWorkbook()
addWorksheet(wb, "Highlighted Table")
# Apply conditional formatting for positive and negative values
highlight_style_pos <- createStyle(bgFill = "#C6EFCE", textDecoration = "bold")
highlight_style_neg <- createStyle(bgFill = "#D9E1F2", textDecoration = "bold")
# Write data to sheet
writeData(wb, sheet = "Highlighted Table", x = data, withFilter = FALSE)
# Highlight rows based on conditions
for (i in seq_len(nrow(data))) {
if (data$Diff[i] %in% top_values$Diff & data$B[i] == 1) {
if (data$Diff[i] > 0) {
addStyle(wb, sheet = "Highlighted Table", style = createStyle(bgFill = "#C6EFCE", textDecoration = "bold"), rows = i + 1, cols = 1:6, gridExpand = TRUE)
} else {
addStyle(wb, sheet = "Highlighted Table", style = createStyle(bgFill = "#D9E1F2", textDecoration = "bold"), rows = i + 1, cols = 1:6, gridExpand = TRUE)
}
}
}
# tabColor <- createStyle(tabColor = "#FFCCCB")
# setSheetColor(wb, sheet = "Highlighted Table", XLC$COLOR.RED)
# Save the workbook
saveWorkbook(wb, "C:../Highlighted_T2_1.xlsx", overwrite = TRUE)