以编程方式为数据表中的数字列设置颜色格式 [英] Programmatically color format numeric columns in a datatable
本文介绍了以编程方式为数据表中的数字列设置颜色格式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我希望为每个数字列设置颜色格式,以便根据每个列的范围显示一个蓝色范围条。这是我要实现的目标的照片。
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
推荐答案
有几项可以改进的地方:
There are a couple of things you can improve:
- 以编程方式定义数字列(传递
sapply(iris,is.numeric)
结果)。 - 要格式化样式,您需要传递原始表(
iris
而不是df
)。由于行名,df
可能具有不同的列。 - 到
styleColorBar
还会传递原始表,而不是df
。
- Programatically define numeric columns (pass
sapply(iris, is.numeric)
result). - To format style you need to pass original table (
iris
instead ofdf
).df
might have different columns, because of row-names. - To
styleColorBar
also pass original table instead ofdf
.
代码:
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')
结果:
这篇关于以编程方式为数据表中的数字列设置颜色格式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文