Search code examples
rconditional-formattingformattable

conditional color format every second row in a column with formattable (or any other package)


I have data table similar to the one below (original is 10 columns and 34 rows). I want to conditionally color format every second row base on the value in each cell. All rows with a numeric should be formated (35, 25, 20).

I also want to only have one of each doublet in the Group column while keeping both the rows they are refering to in the Obesity column. Dont know if this is possible.

>df
Group    Obesity       
1.a      1(ref)          
1.a      35             
2.b      0.6 (0.5,0.7)         
2.b      25              
3.c      0.7 (0.6,0.9)           
3.c      20

This is the code that would work on a normal numeric colum, It also works on the example data, however the colors is not correct.

formattable(df, list(
      Obesity = color_tile("darkorange",  "white") 

    )) 

Reproducible data

 df <- data.frame(Group = c("1.a","1.a","2.b","2.b","3.c","3.c"),
                  Obesity = c("1(ref)",35,"0.6 (0.5,0.7)",25,"0.7 (0.6,0.9)",20),
                  stringsAsFactors = FALSE)

Solution

  • Like this?

    df = data.frame(Group = c('1.a', '1.a', '2.b', '2.b', '3.c', '3.c'),
                    Obesity = c('1(ref)', 35, '0.6 (0.5, 0.7)', 25, '0.7 (0.6, 0.9)', 20))
    library(formattable)
    formattable(df, list(area(row = seq(2, nrow(df), by=2), col = Obesity) ~ 
                           color_tile("transparent", "pink")))
    

    enter image description here

    PS: indeed, the question could be asked in a clearer way ;-)