最新消息:Welcome to the puzzle paradise for programmers! Here, a well-designed puzzle awaits you. From code logic puzzles to algorithmic challenges, each level is closely centered on the programmer's expertise and skills. Whether you're a novice programmer or an experienced tech guru, you'll find your own challenges on this site. In the process of solving puzzles, you can not only exercise your thinking skills, but also deepen your understanding and application of programming knowledge. Come to start this puzzle journey full of wisdom and challenges, with many programmers to compete with each other and show your programming wisdom! Translated with DeepL.com (free version)

javascript - Color differently positive and negative values of DT::Datatable - Stack Overflow

matteradmin7PV0评论

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' : ''"))

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' : ''"))
Share Improve this question edited Aug 23, 2019 at 13:24 Joris C. 6,2643 gold badges14 silver badges29 bronze badges asked Aug 23, 2019 at 11:09 firmo23firmo23 8,4863 gold badges48 silver badges162 bronze badges 1
  • May be useful for you: stackoverflow./questions/47508736/… – Saurabh Chauhan Commented Aug 23, 2019 at 11:14
Add a ment  | 

1 Answer 1

Reset to default 8

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"
    )
Post a comment

comment list (0)

  1. No comments so far