Programmatically color format numeric columns in a datatable

微笑、不失礼 提交于 2019-12-11 09:32:09

问题


I am looking to color format each numeric column so that it shows a blue range bar depending on the range of each column. Here is a photo on what I am trying to achieve.

#Here is the the table I have so far.
#I am adding filters to the columns. This works great

library(DT)
library(magrittr)
df = datatable(iris, filter = 'top', options = list(pageLength = 5, autoWidth = TRUE))

#I try to add the blue bars here to the first 2 numeric columns

df %>%formatStyle(names(df)[1:2],
            background = styleColorBar(range(df[,1:2]), 'lightblue'),
            backgroundSize = '98% 88%',
            backgroundRepeat = 'no-repeat',
            backgroundPosition = 'center')
Error in df[, 1:2] : incorrect number of dimensions

It would also be nice if there was a function to automatically place the blue bars on all numeric columns. Thanks in advance


回答1:


There are a couple of things you can improve:

  • Programatically define numeric columns (pass sapply(iris, is.numeric) result).
  • To format style you need to pass original table (iris instead of df). df might have different columns, because of row-names.
  • To styleColorBar also pass original table instead of df.

Code:

library(magrittr)
library(DT)

# Specify numeric columns
foo <- sapply(iris, is.numeric)

datatable(iris, filter = 'top', options = list(pageLength = 5, autoWidth = TRUE)) %>%
    formatStyle(names(iris)[foo],
            background = styleColorBar(range(iris[, foo]), 'lightblue'),
            backgroundSize = '98% 88%',
            backgroundRepeat = 'no-repeat',
            backgroundPosition = 'center')

Result:



来源:https://stackoverflow.com/questions/54943418/programmatically-color-format-numeric-columns-in-a-datatable

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!