Search code examples
rexcelxlsx

Excel Cell Coloring using xlsx


Initial code:

Lets assume we're using this command to create the dummy data:

Data <- data.frame(
    X = paste(c(sample(1:10),sample(1:10)), collapse=";"),
    Y = sample(c("yes", "no"), 10, replace = TRUE)
)

Output:

                                           X   Y
1  10;7;4;3;8;6;5;2;9;1;3;5;10;2;9;6;8;4;1;7 yes
2  10;7;4;3;8;6;5;2;9;1;3;5;10;2;9;6;8;4;1;7  no
3  10;7;4;3;8;6;5;2;9;1;3;5;10;2;9;6;8;4;1;7  no
4  10;7;4;3;8;6;5;2;9;1;3;5;10;2;9;6;8;4;1;7 yes
5  10;7;4;3;8;6;5;2;9;1;3;5;10;2;9;6;8;4;1;7  no
6  10;7;4;3;8;6;5;2;9;1;3;5;10;2;9;6;8;4;1;7 yes
7  10;7;4;3;8;6;5;2;9;1;3;5;10;2;9;6;8;4;1;7  no
8  10;7;4;3;8;6;5;2;9;1;3;5;10;2;9;6;8;4;1;7 yes
9  10;7;4;3;8;6;5;2;9;1;3;5;10;2;9;6;8;4;1;7 yes
10 10;7;4;3;8;6;5;2;9;1;3;5;10;2;9;6;8;4;1;7 yes

Question:

Using xlsx package I can output the X column data to an excel file colored.

Is there a way where I can color lets say the values bigger then 5 to red and lesser then 5 to blue and put in the same cell everything. Basically I just write this table to an excel but some values are colored.

Thank you in advance,


Solution

  • I doubt it's possible to change Excel's conditional formatting directly from R. So, first open the Excel workbook and set the conditional formatting for the column "X" is going into to whatever color vs value conditions you want. Then when you write from R into the workbook, the coloring will happen.