Currently, color = ifelse('VARIACION'< -0,'#ed1c16','#0ca649')
is evaluating whether the string VARIACION is less than 0. While that is not a particularly meaningful question, R does indeed evaluates that to FALSE (in all your cases) and thus prints things in green as a result.
More generally, you do not want to use ifelse()
in this case. Use something like formatStyle('VARIACION', color = styleInterval(0, c("red", "green"))
instead.
The key here is styleInterval()
which defines cut points and colors for intervals. When you put one cut point (e.g. at 0) and two colors, it uses the first color before the cut point and the second after. You can have multiple intervals though (cut points > 1). You just need one more color than you have cut points (e.g., try something like color = styleInterval(c(0,300000), c("red", "green","blue")))
in my example below).
Below is a working example modified from https://rstudio.github.io/DT/functions.html:
library(DT)
m = cbind(matrix(rnorm(60, 1e5, 1e6), 20), runif(20), rnorm(20, 100))
m[, 1:3] = round(m[, 1:3])
m[, 4:5] = round(m[, 4:5], 7)
colnames(m) = head(LETTERS, ncol(m))
head(m)
datatable(m) %>%
formatCurrency(c('A', 'C')) %>%
formatStyle('A', color = styleInterval(0, c("red", "green")))
Note further that a more proper implementation using ifelse()
still fails since it returns a vector and the color option doesn’t want a vector (as a result it does not throw an error but also doesn’t plot). So again, don’t use ifelse()
here.
#this fails
datatable(m) %>%
formatCurrency(c('A', 'C')) %>%
formatStyle('A', color = ifelse(m[,"A"] < 0, "red", "green"))
2
solved “How can I conditionally format the letters in a datatable?