以编程方式对数据表中的数字列设置颜色格式
Programmatically color format numeric columns in a datatable
我希望对每个数字列进行颜色格式化,以便它根据每列的范围显示蓝色范围条。这是一张关于我想要实现的目标的照片。
#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
如果有自动在所有数字列上放置蓝色条的功能就好了。提前致谢
您可以改进以下几点:
- 以编程方式定义数值列(传递
sapply(iris, is.numeric)
结果)。
- 要格式化样式,您需要传递原始 table(
iris
而不是 df
)。 df
可能有不同的列,因为行名。
- 到
styleColorBar
也传原来的table代替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')
结果:
我希望对每个数字列进行颜色格式化,以便它根据每列的范围显示蓝色范围条。这是一张关于我想要实现的目标的照片。
#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
如果有自动在所有数字列上放置蓝色条的功能就好了。提前致谢
您可以改进以下几点:
- 以编程方式定义数值列(传递
sapply(iris, is.numeric)
结果)。 - 要格式化样式,您需要传递原始 table(
iris
而不是df
)。df
可能有不同的列,因为行名。 - 到
styleColorBar
也传原来的table代替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')
结果: