How highlight specific row values in a table based on a condition

1.1k Views Asked by At

I have a dataframe

structure(list(date = c("4/12/2021", "4/13/2021", "4/14/2021", 
"4/15/2021", "4/16/2021", "4/17/2021", "4/18/2021", "Change", 
"Change (%)"), price1= c(44.42, 43.77, 
43.77, 44.35, 44.4, NA, NA, 0.609999999999999, 1.40126803271157
), price2= c(40.68, 41.73, 45.22, 47.68, 47.35, 44.33, 43.34, 
14.6685714285714, 49.4485913797255)), row.names = c("8", "9", 
"10", "11", "12", "13", "14", "1", "15"), class = "data.frame")

I am trying to use formattable package and formattable() function. It is necessary to highlight cells in rows Change and Change % with green if positive value and red if negative value. I found a similar function here, however it is working only with columns ( `2015`= color_tile(customGreen, customGreen0) part)

Could you help with finding solution how to do it for rows?

1

There are 1 best solutions below

0
On BEST ANSWER

Have a look at the area function. You can specify the rowindex for coloring in the row argument. If you are not interested in coloring the whole row (just rows of certain columns), you can define these columns in the col argument.

Data

df <- structure(list(date = c("4/12/2021", "4/13/2021", "4/14/2021", 
                        "4/15/2021", "4/16/2021", "4/17/2021", "4/18/2021", "Change", 
                        "Change (%)"), price1= c(44.42, 43.77, 
                                                 43.77, 44.35, 44.4, NA, NA, 0.609999999999999, 1.40126803271157
                        ), price2= c(40.68, 41.73, 45.22, 47.68, 47.35, 44.33, 43.34, 
                                     14.6685714285714, 49.4485913797255)), row.names = c("8", "9", 
                                                                                         "10", "11", "12", "13", "14", "1", "15"), class = "data.frame")

Code

library(formattable)

# define row indices
row_change <- which(df$date == "Change")
row_change_percent <- which(df$date == "Change (%)")

# define coloring
red_green_formatter <- formatter("span", 
                                 style = x ~ style(
                                  display = "block",
                                `background-color` = ifelse(x < 0, "red", 
                                                ifelse(x > 0, "lightgreen", "white"))))

# set formattable and define coloring for rows 8 and 9 for every column but not the first
formattable(df,
            list(area(row = row_change:row_change_percent,
                      col = -1) ~ red_green_formatter))

enter image description here