table 中的单元格的条件样式基于每行不同的值范围 (R)

Conditional styling of cells in a table based on a value range that differs per row (R)

我想创建一些 tables,其中来自多列的值根据每行不同的范围(并在列 'min' 和 'max').作为示例,我创建了以下内容:

a <- c('A', 'B', 'C', 'D', 'E')
b <- c(20, 25, 40, 55, 60)
c <- c(60, 30, 80, 50, 60)
min <- c(15, 20, 40, 55, 55)
max <- c(25, 30, 50, 65, 65)

df <- data.frame(a, b, c, min, max)

a  b  c min max
A 20 60  15  25
B 25 30  20  30
C 40 80  40  50
D 55 50  55  65
E 60 60  55  65

table.df <- df[,1:3]%>%
      select(a, everything())%>%
      kable("html", escape = F) %>%
      kable_styling(bootstrap_options = "striped", full_width = F, position = "left")

这给了我一个 table,其中没有显示最小值和最大值的列(如我所愿)。但我想添加一个条件语句,其中 'b' 和 'c' 列中超出 'min' 和 'max' 列定义范围的值变为红色(或否则这些细胞的背景)。 不太熟悉样式 tables,因此非常感谢任何帮助!

包 tableHTML 为 table 样式提供了很多选项,特别是如果您使用 html 代码的一些技巧,例如解决问题的一种方法是以下:

基于这里的回答

您修改满足条件的数据以包括文本格式(或任何其他html格式、字体颜色、背景颜色.....),然后将其传递给tableHTML(),并使用escape=FALSE

library(tableHTML)
library(dplyr)

a <- c('A', 'B', 'C', 'D', 'E')
b <- c(20, 25, 40, 55, 60)
c <- c(60, 30, 80, 50, 60)
min <- c(15, 20, 40, 55, 55)
max <- c(25, 30, 50, 65, 65)

df <- data.frame(a, b, c, min, max)

df %>% 
  mutate(b = ifelse(b < min | b > max, paste0('<font color="red">', b, '</font>'), b),
         c = ifelse(c < min | c > max, paste0('<font color="red">', c, '</font>'), c)) %>% 
 `[`(1:3) %>%
  tableHTML(escape = FALSE, rownames = FALSE, 
            widths = rep(50, 3), theme = 'scientific')

这就是结果

或者可能有两个条件和两种颜色:

df %>% 
  mutate(b = ifelse(b < min ,
                    paste0('<span style="background-color:#ccccff">', b, '</span>'), 
                    ifelse( b > max, paste0('<span style="background-color:#ff9999">', b, '</span>'), 
                            b)),
         c = ifelse(c < min , 
                    paste0('<span style="background-color:#ccccff">', c, '</span>'), 
                    ifelse( c > max,  paste0('<span style="background-color:#ff9999">', c, '</span>'), 
                            c))) %>% 
  `[`(1:3) %>%
  tableHTML(escape = FALSE, rownames = FALSE, 
            widths = rep(50, 3), theme = 'scientific')

你得到:

该软件包提供了很多格式设置选项,甚至还有条件格式(尽管不适用于这种情况),请查看此处以了解您还可以使用该软件包做什么:

tableHTML Basics

conditional formatting

更新

有很多选项可以修改数据框中未知数量的列,我更喜欢使用 apply 函数,例如:

定义一个函数来修改列:

(在这个函数中col是任意向量,min_col是包含下界的向量,max_col是包含上界的向量)

add_format <- function(col, min_col, max_col){
  if(!is.numeric(col)){
    return(as.character(col))
  }else{
    new_col <- ifelse(col < min_col | col > max_col, 
                      paste0('<font color="red">', col, '</font>'), col)
    return(new_col)
  }
}

现在将此函数应用于 df 中的所有列,将其转换为 data.frame,然后其余部分相同

df %>% 
  sapply(add_format, df$min, df$max)  %>% 
  as.data.frame() %>% 
  `[`(1:3) %>%
  tableHTML(escape = FALSE, rownames = FALSE, 
            widths = rep(50, 3), theme = 'scientific')

您还可以查看函数 mutate_ifmutate_all,它们也可以与一些游戏一起工作