Conditional formatStyle in DT

2020-07-24 06:53发布

问题:

I want to color rows in column A by values in column B.

The code below is based on the example from the vignette Link, but shows only the condition for two columns: mobile_number by mobile_flag.

Data:

head(test[, c("EMBG","mobile_number", "home_number",  "mobile_flag", "home_number_flag")])
          EMBG mobile_number      home_number mobile_flag
1 101001455126   075-201-543      02/2446-275     correct
2 101010455015   55555555555      55555555555   incorrect
3 101014455095             0                0   incorrect
4 101947455134   075/482-356      02/2460-020     correct
5 101952450264  070 22 16 18 ----------------     correct
6 101953450012             0      02/2446-276   incorrect
  home_number_flag
1          correct
2        incorrect
3        incorrect
4          correct
5        incorrect
6          correct

My DT table:

> datatable(test) %>% formatStyle(
+   'mobile_number', 'mobile_flag',
+   backgroundColor = styleEqual(c("correct", "incorrect"), c('green', 'red'))) 

However, I want to simultaniouslly color both mobile_number and home_number, based on home_number_flag and mobile_flag, respectivly.

Any ideas how?

回答1:

Try something like this:

library(DT)
datatable(test) %>%
    formatStyle(
        columns = c("mobile_number", "home_number"),
        valueColumns = c("mobile_flag", "home_number_flag"),
        backgroundColor = styleEqual(c("correct", "incorrect"), 
                                     c("green", "red"))
    )

columns specifies which columns you would like to conditionally format. valueColumns specifies which columns should be evaluated using the conditions specified in styleEqual of backgroundColor.

Note that order in columns corresponds with order in valueColumns (e.g "mobile_number" is conditionally colored by "mobile_flag").



标签: r dt htmlwidgets