Reactive coloring in DT table

Hi all,

Need help. Below is the application. ColB is to be colored based on numbers in ColA. Below is the condition table

image

Just to brief : if ColB is 2, So it is lesser than 6 (12/2), it should be red and similarly for others

---
title: "Untitled"
runtime: shiny
output: 
  flexdashboard::flex_dashboard:
    orientation: columns
    vertical_layout: fill
---

```{r setup, include=FALSE}
library(flexdashboard)
library(DT)
```

```{r}
tab1 <- data.frame(ColA = c(12,34,45,56), ColB = c(2,32,30,56))
```

Column {data-width=650}
-----------------------------------------------------------------------

### Chart A

```{r}
DT::DTOutput("table1")
output$table1 <- DT::renderDT(
    datatable(tab1))
```

Hi Team,

I tried to build the code myself and came up with below . But looks like there is some issue in the code . I have attached the output also below and the logic is not working properly.

Output

So As per the code, the highlighted arrows are showing color.

  1. First Arrow (Supposed to be red but it is showing as Yellow)
  2. Second Arrow (Supposed to be Yellow but it is showing as Green)

Note : ColB is randomly generated and you may not see these numbers when you run it. But you observe randomly, this issue you will find for sure when you run as well. Not sure what is wrong in the code . Below is the code for your reference

---
title: "Untitled"
runtime: shiny
output: 
  flexdashboard::flex_dashboard:
    orientation: columns
    vertical_layout: fill
---

```{r setup, include=FALSE}
library(flexdashboard)
library(DT)
library(tidyverse)
library(dplyr)
```

```{r}
tab1 <- data.frame(ColA = c(3:40))
tab1 <- tab1 %>% rowwise() %>% mutate(ColB = sample(1:ColA, 1))
tab1 <- as.data.frame(tab1)
```

Column {data-width=650}
-----------------------------------------------------------------------

### Chart A

```{r}
DT::DTOutput("table1")

col_format <- ifelse(tab1$ColA == tab1$ColB,'green',
                     ifelse(tab1$ColA/2 <= tab1$ColB,'yellow',
                            ifelse(tab1$ColA/2 > tab1$ColB,'red','')))
 
output$table1 <- DT::renderDT(
    datatable(tab1)
     %>% formatStyle('ColB',  backgroundColor = styleEqual(tab1$ColB, col_format))
    )
```



This topic was automatically closed 54 days after the last reply. New replies are no longer allowed.

DT::DTOutput("table1")

tab1$col_format <- ifelse(tab1$ColA == tab1$ColB,'green',
                     ifelse(tab1$ColA/2 <= tab1$ColB,'yellow',
                            ifelse(tab1$ColA/2 > tab1$ColB,'red','')))

output$table1 <- DT::renderDT(
  datatable(tab1 ,options = list(
    columnDefs = list(list(targets = 3, visible = FALSE))
))
  %>% formatStyle('ColB','col_format',  backgroundColor =styleEqual('col_format','col_format'))
)

documentation:
https://rstudio.github.io/DT/010-style.html
3rd code snippet