2017-10-20 117 views
1

我有一个data.table我用DT显示。在两列中,我显示百分比并希望显示背景条。但是列数可以根据所选表格而改变。将有一个或两个百分比列。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* 

所以,我怎么能动态地选择要显示的列的吧?

任何帮助非常感谢。

回答

1

问题出自range()styleColorBar(),因为它期望一个数字或字符向量。

如果你只传递你想应用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') 

这将返回

enter image description here

+0

完美,没有一个大的改写。谢谢。 –