Reputation: 7464
I want to apply formatStyle
function to different columns in my table. I can easily apply the same style to all the columns, or to some subset of columns, e.g.
divBySum <- function(x) x/sum(x)
output$test <- DT::renderDataTable(
datatable(mutate_each(mtcars, funs(divBySum)),
options = list(searching = FALSE,
paging = FALSE,
dom = 't'),
rownames = FALSE) %>%
formatStyle(colnames(mtcars),
background = styleColorBar(c(0, 1), 'lightgray'),
backgroundSize = '98% 88%',
backgroundRepeat = 'no-repeat',
backgroundPosition = 'center') %>%
formatPercentage(colnames(mtcars))
)
However I would like to apply different formatStyle
to each of the columns. For example, I would like to define maximal length of bar to styleColorBar(c(0, max(x)), 'lightgray')
, where x
is a column, or different colors for them.
I would like to do this with some function that takes as input a vector of column names. Is there any nice, clever way to do this?
Upvotes: 5
Views: 2006
Reputation: 21425
You could use mapply
for this and loop through the columns to add whatever color you want, here's an example:
data <- datatable(mtcars)
mapply(function(column,color){
data <<- data %>% formatStyle(column,
background = styleColorBar(c(0, max(mtcars[[column]])), color),
backgroundSize = '98% 88%',
backgroundRepeat = 'no-repeat',
backgroundPosition = 'center')
},colnames(mtcars),rep_len(c("green","red","yellow"),length.out = ncol(mtcars)))
Upvotes: 4