首页 > 解决方案 > 以编程方式对数据表中的数字列进行颜色格式化

问题描述

我正在寻找颜色格式每个数字列,以便它根据每列的范围显示一个蓝色范围栏。这是一张关于我想要实现的目标的照片。在此处输入图像描述

#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

如果有一个功能可以自动将蓝色条放置在所有数字列上,那就太好了。提前致谢

标签: rshinydatatablesdt

解决方案


您可以改进以下几点:

  • 以编程方式定义数字列(传递sapply(iris, is.numeric)结果)。
  • 要格式化样式,您需要传递原始表格(iris而不是df)。df由于行名,可能有不同的列。
  • 还要通过styleColorBar原始表而不是df.

代码:

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

结果:

在此处输入图像描述


推荐阅读