使用条件语句更改表中值的颜色(kableextra)

时间:2019-04-09 03:03:02

标签: r

我正在尝试使用kableextra创建一个表。我想更改值的颜色,以便使用cell_spec函数通过遍历数据帧的循环以及指定条件值的条件语句,将> = 85的值更改为绿色,将<50的值更改为红色。需要更改的值。

我已经能够使用kableextra文档更改单个值并指定要更改的每一列,但是除非有更好的方法,否则我想使用多个if语句而不是ifelse。

到目前为止,我一直在使用的代码是:

library(dplyr)
library(kableExtra)

Subject <- c("Database", "Java", "C++", "Physics", "Mathematics", "English", "Chemistry", "Networks", "Security")
A <- c(69, 64, 70, 57, 80, 34, 45, 56, 96)
B <- c(70, 74, 68, 76, 71, 56, 56, 45, 30)
C <- c(84, 58, 87, 78, 67, 67, 43, 34, 56)
D <- c(78, 83, 68, 72, 90, 48, 23, 23, 46)
E <- c(79, 55, 91, 71, 34, 26, 76, 67, 75)
F <- c(80, 72, 64, 45, 66, 76, 45, 56, 54)
G <- c(90, 67, 76, 51, 45, 59, 33, 64, 34)
H <- c(60, 59, 88, 90, 76, 34, 43, 72, 45)


student_results <- data.frame(Subject, A, B, C, D, E, F, G, H)

rownames(student_results) <- c("Database", "Java", "C++", "Physics", "Mathematics", "English", "Chemistry", "Networks", "Security")

student_results %>%
    mutate(
      A = cell_spec(A, "html", color = ifelse(A >= 85, "coral", "black")),
      B = cell_spec(B, "html", color = ifelse(B >= 85, "coral", "black")),
      C = cell_spec(C, "html", color = ifelse(C >= 85, "coral", "black")),
      D = cell_spec(D, "html", color = ifelse(D >= 85, "coral", "black")),
      E = cell_spec(E, "html", color = ifelse(E >= 85, "coral", "black")),
      F = cell_spec(F, "html", color = ifelse(F >= 85, "coral", "black")),
      G = cell_spec(G, "html", color = ifelse(G >= 85, "coral", "black")),
      H = cell_spec(H, "html", color = ifelse(H >= 85, "coral", "black"))
    ) %>%
    kable(format = "html", escape = FALSE) %>%
    kable_styling("striped", full_width = FALSE)

这成功更改了一个值范围,但是我希望能够设置多个范围的格式,并且避免在处理大型数据集时单独指定每一列。

谢谢

1 个答案:

答案 0 :(得分:0)

要一次更改多个列,可以使用mutate_at。要具有多个条件,可以使用嵌套的ifelse条件。嵌套ifelse会在一段时间后变得笨拙,因此您可以查看case_when

student_results %>%
    mutate_at(vars(A:H), ~ cell_spec(
        ., "html", 
        color = ifelse(. >= 85, "coral", ifelse(. < 50, "red", "black"))
    )) %>%
    kable(format = "html", escape = FALSE) %>%
    kable_styling("striped", full_width = FALSE)