【问题标题】:Programmatically color format numeric columns in a datatable以编程方式对数据表中的数字列进行颜色格式化
【发布时间】:2019-07-23 09:57:20
【问题描述】:

我希望为每个数字列设置颜色格式,以便根据每列的范围显示一个蓝色范围栏。这是一张关于我想要实现的目标的照片。

#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

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

【问题讨论】:

    标签: r shiny datatables dt


    【解决方案1】:

    您可以改进以下几点:

    • 以编程方式定义数字列(传递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')
    

    结果:

    【讨论】:

    • 非常感谢宝!!你知道是否有办法比较每个单独列的范围而不是整个数据框的范围?例如,与花瓣宽度范围相比,0.2 的花瓣宽度实际上可能很大。
    • @JordanWrong 可以通过按列缩放数据来完成。您能否将此作为新问题发布,因为这与您的原始问题非常不同
    • 我已经添加了一个新线程,如果你有时间,请看一下。 stackoverflow.com/questions/54950917/…
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-09-13
    • 2011-06-29
    • 2013-06-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多