【问题标题】:Conditional formatting multiple columns in reactable在可反应中条件格式化多列
【发布时间】:2021-05-01 01:00:52
【问题描述】:

我已经为此苦苦挣扎了一段时间,但无法理解它。

我想生成一个可反应的表格,但有条件地格式化每个(数字)列并带有背景阴影。只要我手动输入每列的名称,我就知道如何将其应用于列。但关键是该表可以有任意数量(可能很大)的列,所以我想自动将其应用于所有列。

重要的是,列代表不同尺度的不同变量,因此必须为每列分别应用格式。我猜秘诀是创建一个大的命名列表,即用其他列名扩展coldefs 列表。

下面是一个只有一列的示例。我试图扩展它,但陷入了巨大的混乱,所以我不会在这里粘贴混乱的代码来迷惑任何人。非常感谢任何帮助。

library(reactable)

df <- mtcars
df$mpg[2] <- NA

# Colour map for conditional formatting
orange_pal <- function(x){
  if (!is.na(x)){
    rgb(colorRamp(c("#ffe4cc", "#ffb54d"))(x), maxColorValue = 255)
  } else {
    "#e9e9e9" #grey
  }
}

# function which returns background colour based on cell value (using colour map)
stylefunc <- function(value) {
  normalized <- (value - min(mtcars$mpg)) / (max(mtcars$mpg) - min(mtcars$mpg))
  color <- orange_pal(normalized)
  list(background = color)
}

# list giving column formatting (using style function)
coldefs <- list(mpg = reactable::colDef(
  style = stylefunc
))

# create table
reactable(df,
          columns = coldefs)

【问题讨论】:

    标签: r shiny reactable


    【解决方案1】:

    好吧,就像去看医生一样,我一寻求帮助就自己找到了解决方案。嗯,就是这样。可能会帮助其他人。诀窍是colDef()style 元素也允许使用列名的函数。使用它,我能够自动获取每列的最大值和最小值。

    library(reactable)
    library(magrittr)
    
    df <- mtcars
    df$mpg[2] <- NA
    
    # Colour map for conditional formatting
    orange_pal <- function(x){
      if (!is.na(x)){
        rgb(colorRamp(c("#ffe4cc", "#ffb54d"))(x), maxColorValue = 255)
      } else {
        "#e9e9e9" #grey
      }
    }
    
    # function which returns background colour based on cell value (using colour map)
    # also takes column name as an input, which allows to get max and min
    stylefunc <- function(value, index, name) {
      normalized <- (value - min(mtcars[name], na.rm = T)) /
        (max(mtcars[name], na.rm = T) - min(mtcars[name], na.rm = T))
      color <- orange_pal(normalized)
      list(background = color)
    }
    
    # list giving column formatting (using style function) for single column
    coldefs <- list(
      reactable::colDef(style = stylefunc)
    )
    
    # get names of numerical cols
    numcols <- mtcars %>% dplyr::select(where(is.numeric)) %>% colnames()
    # replicate list to required length
    coldefs <- rep(coldefs,length(numcols))
    # name elements of list according to cols
    names(coldefs) <- numcols
    
    # create table
    reactable(df,
              columns = coldefs)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-10-23
      • 2021-11-26
      • 1970-01-01
      • 1970-01-01
      • 2016-01-30
      • 2014-12-25
      • 1970-01-01
      相关资源
      最近更新 更多