我想将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))
)
Run Code Online (Sandbox Code Playgroud)
但是我想对每一列应用不同的方法。 formatStyle
例如,我想定义 bar 的最大长度styleColorBar(c(0, max(x)), 'lightgray')
,其中x
是一列,或者它们的不同颜色。
我想使用一些将列名称向量作为输入的函数来执行此操作。有什么好的、聪明的方法可以做到这一点吗?
您可以使用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)))
Run Code Online (Sandbox Code Playgroud)