2017-10-20 1 views
1

私はDTで表示しているdata.tableがあります。 2つの列で、パーセンテージを表示し、背景バーを表示したい。ただし、選択するテーブルによって列の数が変わる可能性があります。 1つまたは2つの割合の列があります。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

パーフェクト、大きな書き換えずに返されます。ありがとうございました。 –

関連する問題