多列DT R上的formatStyle [英] formatStyle over multiple columns DT R

查看:34
本文介绍了多列DT R上的formatStyle的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个带一个ID列和多个数字列的data.frame,数字列的数量可以不同.在这些数字列中,我要为该列上方的所有值涂成绿色,而在该列下方的所有值涂成红色.下面的代码给出了我想要的结果,但它不是用于具有或多或少数字列的数据帧的通用代码.

I have a data.frame with one ID column and multiple numeric columns, the amount of numeric columns can differ. 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?

推荐答案

您可以通过

(不适用于不同列中的相同值)

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))

更新

您可以像

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"),"}" ))
  )
) 

这篇关于多列DT R上的formatStyle的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆