I am trying to color the positive and negative values of a certain column (third) of a DT::Datatable
with green and red colors respectively based on this code chunk, but I am not a javascript user. Is there any way to set this?
library(DT)
datatable(head(iris)) %>%
formatStyle(1:4, color = JS("value % 1 === 0 ? 'red' : ''"))
You can use DT::styleInterval
for this:
library(DT)
## data (iris dataset contains no negative values)
dat <- data.frame(
letters = LETTERS[1:26],
numbers = sample(c(-1, -0.5, 0, 0.5, 1), 26, replace = TRUE)
)
datatable(dat) %>%
formatStyle(
columns = "numbers",
color = styleInterval(cuts = 0, values = c("red", "green")),
fontWeight = "bold"
)
NB: If zero values should be ignored, you can set a black color to a small region around zero:
eps <- 1E-5
datatable(dat) %>%
formatStyle(
columns = "numbers",
color = styleInterval(cuts = c(-eps, eps), values = c("red", "black", "green")),
fontWeight = "bold"
)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.