1

I would like to highlight red if the number is < a user-defined threshold (e.g. -5) and highlight green if the number if > another user-defined threshhold (e.g. +5). Otherwise, it is shaded grey. Any help is greatly appreciated! Thank you.

It's similar to this question but not the same. styleColorBar Center and shift Left/Right dependent on Sign

Test data

data <- data.frame(a=c(rep("a",10)),value=c(-8,-7,-2,-3,0,6,2, 7,3,4))
Ketty
  • 811
  • 10
  • 21

1 Answers1

1

Try:

color_from_middle <- function (data,low,high, colorlow,colorhigh,colordefault) 
{
  max_val=max(abs(data))
  JS(sprintf("isNaN(parseFloat(value)) || 
              value < %s ? 'linear-gradient(90deg, transparent, transparent ' + (50 + value/%s * 50) + '%%, %s ' + (50 + value/%s * 50) + '%%,%s  50%%,transparent 50%%)' :
              value > %s ? 'linear-gradient(90deg, transparent, transparent 50%%, %s 50%%, %s ' + (50 + value/%s * 50) + '%%, transparent ' + (50 + value/%s * 50) + '%%)':
              value < 0  ? 'linear-gradient(90deg, transparent, transparent ' + (50 + value/%s * 50) + '%%, %s ' + (50 + value/%s * 50) + '%%,%s  50%%,transparent 50%%)':
                           'linear-gradient(90deg, transparent, transparent 50%%, %s 50%%, %s ' + (50 + value/%s * 50) + '%%, transparent ' + (50 + value/%s * 50) + '%%)'",
             low,max_val,colorlow,max_val,colorlow,high,colorhigh,colorhigh,max_val,max_val,max_val,colordefault,max_val,colordefault,colordefault,colordefault,max_val,max_val))
}

datatable(data) %>%
  formatStyle('value',background=color_from_middle(data$value,-5,5,'red','blue','grey'))

This relies on JavaScript conditional operator : condition ? true : false

enter image description here

Waldi
  • 39,242
  • 6
  • 30
  • 78