简体   繁体   English

多列DT R上的formatStyle

[英]formatStyle over multiple columns DT R

I have a data.frame with one ID column and multiple numeric columns, the amount of numeric columns can differ. 我有一个带有一个ID列和多个数字列的data.frame,数字列的数量可以不同。 Of these numeric columns I want to color all values above the column mean green and all values below the column mean red. 在这些数字列中,我想为列上方的所有值着色为绿色,列下方的所有值均为红色。 The code below give my desired outcome, but it is not a generic code for data frames with more or less numeric columns. 下面的代码给出了我想要的结果,但它不是具有更多或更少数字列的数据框的通用代码。

library(DT)

data2 <- cbind(ID = "some ID",iris[,1:4])

    datatable(
      data2, rownames = FALSE, class = 'cell-border stripe',
      options = list(
        dom = 't', pageLength = -1, lengthMenu = list(c(-1), c('All'))
      )
) %>%
  formatStyle(colnames(data)[2], backgroundColor = styleInterval(mean(data[,2]), c("red","green"))) %>%
  formatStyle(colnames(data)[3], backgroundColor = styleInterval(mean(data[,3]), c("red","green"))) %>%
  formatStyle(colnames(data)[4], backgroundColor = styleInterval(mean(data[,4]), c("red","green"))) %>%
  formatStyle(colnames(data)[5], backgroundColor = styleInterval(mean(data[,5]), c("red","green")))

I would like to replace the code above with the code below but that does not work. 我想用下面的代码替换上面的代码,但这不起作用。 The code below will also work when the number of numeric columns changes. 当数字列的数量发生变化时,下面的代码也可以使用。

datatable(
  data2, rownames = FALSE, class = 'cell-border stripe',
  options = list(
    dom = 't', pageLength = -1, lengthMenu = list(c(-1), c('All'))
  )
) %>%
  formatStyle(colnames(data2)[2:ncol(data2)], backgroundColor = styleInterval(colMeans(data2[,2:ncol(data2)]), c("red","green")))

Is this possible? 这可能吗? So yes, how? 是的,怎么样?

You can do it with addition calculation like 您可以通过添加计算来完成

(Not work with same value in different column) (在不同列中不能使用相同的值)

hepl_1=sapply(2:ncol(data2),function(i)  ifelse(data2[[i]]>=mean(data2[[i]]),"rgb(255,0,0)","rgb(0,255,0)"))
help_3=as.matrix(data2[2:ncol(data2)])

datatable(
  data2, rownames = FALSE, class = 'cell-border stripe',
  options = list(
    dom = 't', pageLength = -1, lengthMenu = list(c(-1), c('All'))
  )
) %>%
  formatStyle(colnames(data2)[2:ncol(data2)], backgroundColor = styleEqual(help_3, hepl_1))

Update 更新

You can generate rowCallback like 你可以像生成rowCallback一样

datatable(
  data2, rownames = FALSE, class = 'cell-border stripe',
  options = list(
    dom = 't', pageLength = -1, lengthMenu = list(c(-1), c('All')),
    rowCallback=JS(paste0("function(row, data) {\n",
                          paste(sapply(2:ncol(data2),function(i) paste0("var value=data[",i-1,"]; if (value!==null) $(this.api().cell(row,",i-1,").node()).css({'background-color':value <=", mean(data2[[i]])," ? 'red' : 'green'});\n")
                          ),collapse = "\n"),"}" ))
  )
) 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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