0

我已经为此苦苦挣扎了一段时间,但无法解决这个问题。

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

重要的是,列代表不同尺度的不同变量,因此必须为每列单独应用格式。我猜秘诀是创建一个大的命名列表,即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)
4

1 回答 1

5

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

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)
于 2021-01-27T08:25:57.160 回答