2016-03-04 45 views
3

我想formatStyle功能适用于不同的列在我的表。我可以轻松地将相同的样式应用于所有列或列的某个子集,例如,数据表:不同formatStyle适用于每一列

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)) 
) 

不过,我想申请不同formatStyle到每一列。例如,我想限定杆的最大长度来styleColorBar(c(0, max(x)), 'lightgray'),其中x是一列,或不同颜色他们。

我想用一些函数作为输入列名的载体来做到这一点。有没有什么好的,聪明的方法来做到这一点?

+0

不知'tagList'可以在这里使用? https://github.com/hrbrmstr/vegalite/issues/3 –

回答

3

您可以使用mapply,这和遍历栏添加任何你想要的颜色,这里有一个例子:

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))) 
+0

做我错误地再现或者是这个方法不工作了? – BigDataScientist

相关问题