Reputation: 313
I have a data.table I am displaying with DT. In two columns I display percentages and want to show background bars. However the number of columns can change depending on the table chosen. There will either be one or two percentage columns.
Here's some dummy data and my approach so far which unsuccessfully uses 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')
Unfortunately this create the error:
*Error in FUN(X[[i]], ...) : only defined on a data frame with all numeric variables*
So how can I dynamically select the columns to display the bars?
Any help much appreciated.
Upvotes: 2
Views: 633
Reputation: 6813
The problem comes from range()
in styleColorBar()
, as it expects a numeric or character vector.
If you pass only the values of the columns you want to apply css to it will work. You can use styleColorBar = unlist(x[, .SD, .SDcols=grep("%", colnames(x), value=TRUE)])
to do just that:
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')
This will return
Upvotes: 2