【问题标题】:DT data table display errorDT数据表显示错误
【发布时间】:2018-04-01 13:49:45
【问题描述】:

我有一个 data.table 我用 DT 显示。在两列中,我显示百分比并希望显示背景条。但是,列数可能会根据选择的表而改变。将有一个或两个百分比列。

这里有一些虚拟数据和我迄今为止未能成功使用 grep 的方法。

a <- c(45, 143, 123, 120, 118, 109, 94, 81)
b <- c(54, 132, 119, 113, 108, 104, 99, 91)
a2 <- round(a/sum(a)*100,2)
b2 <- round(b/sum(b)*100,2)

dt <- data.table("Age" = c("-20", "20-30", "30-40", "40-50",
                           "50-60", "60-70", "70-80", "80+"),
                 "Group A" = a,
                 "Group A %" = a2,
                 "Group B" = b,
                 "Group B %" = b2)


if(sample(c(0,1), 1)==1) x <- dt else x <- dt[ ,c(1:3)]

DT::datatable(x,
              rownames = FALSE,
              extensions = c('FixedColumns'),
              class = 'cell-border stripe',
              options = list(dom = 't',
                             pageLength = nrow(x),
                             columnDefs = list(list(className = 'dt-center', targets = 0:(ncol(x)-1)))
                             )
              ) %>%
  formatStyle(
    grep("%", colnames(x), value=TRUE),
    background = styleColorBar(x[, .SD, .SDcols=grep("%", colnames(x), value=TRUE)], 'steelblue'),
    backgroundSize = '50% 50%',
    backgroundRepeat = 'no-repeat',
    backgroundPosition = 'right')

不幸的是,这会产生错误:

*Error in FUN(X[[i]], ...) : only defined on a data frame with all numeric variables*

那么如何动态选择列来显示条形?

非常感谢任何帮助。

【问题讨论】:

    标签: r data.table dt


    【解决方案1】:

    问题来自styleColorBar() 中的range(),因为它需要一个数字或字符向量。

    如果您只传递要应用 css 的列的值,它将起作用。您可以使用styleColorBar = unlist(x[, .SD, .SDcols=grep("%", colnames(x), value=TRUE)]) 来做到这一点:

    DT::datatable(x,
                  rownames = FALSE,
                  extensions = c('FixedColumns'),
                  class = 'cell-border stripe',
                  options = list(dom = 't',
                                 pageLength = nrow(x),
                                 columnDefs = list(list(className = 'dt-center', targets = 0:(ncol(x)-1)))
                  )
    ) %>%
      formatStyle(
        columns = grep("%", colnames(x), value=TRUE),
        background = styleColorBar(unlist(x[, .SD, .SDcols=grep("%", colnames(x), value=TRUE)]), 'steelblue'),
        backgroundSize = '50% 50%',
        backgroundRepeat = 'no-repeat',
        backgroundPosition = 'right')
    

    这将返回

    【讨论】:

    • 完美且无需大量重写。谢谢。
    猜你喜欢
    • 1970-01-01
    • 2021-09-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-03-28
    • 2017-11-06
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多