Datatable:对每个列应用不同的格式样式

时间:2021-01-06 14:26:13

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.

我想对表中的不同列应用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))
  )

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.

但是,我希望对每个列应用不同的格式样式。例如,我想定义styleColorBar的最大长度(c(0, max(x)), 'lightgray'),其中x是一列,或者是不同的颜色。

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?

我想用一个函数来做这个函数,这个函数的输入是一个列名的向量。有什么好办法吗?

1 个解决方案

#1


3  

You could use mapply for this and loop through the columns to add whatever color you want, here's an example:

你可以使用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)))

#1


3  

You could use mapply for this and loop through the columns to add whatever color you want, here's an example:

你可以使用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)))