多列DT R上的formatStyle

时间:2016-06-27 09:05:12

标签: r dt

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

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

我想用下面的代码替换上面的代码,但这不起作用。当数字列数发生变化时,下面的代码也会起作用。

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

这可能吗?是的,怎么样?

1 个答案:

答案 0 :(得分:3)

您可以使用

等附加计算来完成此操作

(在不同的列中不能使用相同的值)

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

更新

您可以生成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"),"}" ))
  )
)