简体   繁体   中英

How to change the font color of a DT table based on another matrix in R

I have two matrices: the first has the data that I want to show and the other has the values that are going to be used to select the color of the font. The thing is that I don't know how to change the color based on the second matrix with the DT package in R, i have done it with respect to columns in the main matrix but can't figure out how to do it with respect to another matrix.

This is what i have:

data = matrix(rnorm(100),10,10)
colnames(data) = as.character(seq(as.Date(Sys.Date()),as.Date(Sys.Date()+10), length.out = 10))
data_2 = matrix(runif(100),10,10)
colnames(data_2) = as.character(1:10)
data_final = cbind(data,data_2)

datatable(data_final,
          options = list(paging = FALSE, dom = 'tip',columnDefs = list(list(visible=F,
          targets =  c(10:20)))))%>%
  formatPercentage(colnames(data_final),2)

I think it shoud be something like this:

  formatStyle(1:4, valueColumns=5:8,
              color = JS("value < 0 ? 'red' : value > 0 ? 'green' : 'blue'"))

where 1:4 are the columns I want to change the color, 5:8 are the values to compare, but in the color = JS it should be change in some way that it compares the colum 1 with the column 5, and so on to decided the color.

You could just use styleInterval like this:

formatStyle(columns = 1:10, valueColumns = 11:20, color = styleInterval(c(-1e-10, 1e-10), c('red', 'blue', 'green')))

Here we use two breaks at -1e-10 and +1e-10 . Everything in between, so basically the zeros, will be blue.

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM