'How can I set a colour gradient background to cells by row (say white to red) in R using DT package?

I have a 2x91 datatable in R with columns: 'Item' and 'normal_mElo_student'.

The are 91 'Items' in the 'Item' column called 'PC01', 'PC02'...'PC91', with numerical values in the 'normal_mElo_student' column. 'normal_mElo_student' has MIN=0 and MAX=1. The rows are sorted into descending order of 'normal_mElo_student'.

Similar to a heat map, I want to colour the background of the cells in the 'normal_mElo_student' column in a colour gradient that matches its descending order. This would be from white through to red, i.e, 91 separate shades of white to pink to red, with the cell in row 1 (containing 1) as the reddest red, and the cell in row 91 (containing 0) would be white.

I'm a real novice when it comes to R. So far I have got to the following, which colours my cells blue when >0.5 and red when <0.5, but I would like to change this to the shades of red. My issue is that the colour isn't determined by the contents of the cell, which seems to be what the function styleInterval() calls for, rather I'd like to colour by the row number.

#arranging rows in descending order 
df <- arrange(df, desc(normal_mElo_student))

#removing supervisor column
student.sort.df <- subset(df, select=-(normal_mElo_supervisor))

#producing datatable
df.dt <- datatable(student.sort.df)

#attempting to format datatable
formatStyle(df.dt, 'normal_mElo_student', backgroundColor= styleInterval(0.5, c('red','blue')))

I have a second table of the same structure but the second column is 'normal_mElo_supervisor'. I would like to colour the cells in this column the same shade of white/pink/red as the cell in 'normal_mElo_student', matching with the item code (PC01 to PC91).

Thank you so much for your help in advance!!



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source