【问题标题】:Datatable: apply different formatStyle to each column数据表:对每一列应用不同的格式样式
【发布时间】:2016-03-04 11:33:12
【问题描述】:

我想将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 是一列,或者它们的颜色不同。

我想使用一些将列名向量作为输入的函数来执行此操作。有什么好的、聪明的方法可以做到这一点?

【问题讨论】:

标签: r shiny


【解决方案1】:

您可以为此使用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)))

【讨论】:

  • 是我复制错误还是这种方法不再有效?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-12-29
  • 2011-05-12
  • 1970-01-01
  • 2020-08-02
  • 1970-01-01
相关资源
最近更新 更多