-->

Programmatically color format numeric columns in a

2019-07-24 22:34发布

问题:

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: