Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/r/83.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
使用条件语句更改表中值的颜色(kableextra)_R - Fatal编程技术网

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

使用条件语句更改表中值的颜色(kableextra),r,R,我正在尝试使用kableextra创建一个表。我想更改值的颜色,使那些>=85的值变为绿色,% 在(vars(A:H),~cell_规范中进行变异( “html”, 颜色=ifelse(.>=85,“珊瑚”,ifelse(.% kable(format=“html”,escape=FALSE)%>% 可折叠样式(“条纹”,全宽=假)

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

我已经能够使用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)
库(dplyr)
图书馆(kableExtra)
科目%
可折叠样式(“条纹”,全宽=假)
这成功地更改了一个范围的值,但我希望能够格式化多个范围,并避免在处理大型数据集时需要单独指定每一列


感谢

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

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)
student\u结果%>%
在(vars(A:H),~cell_规范中进行变异(
“html”,
颜色=ifelse(.>=85,“珊瑚”,ifelse(.<50,“红色”,“黑色”))
)) %>%
kable(format=“html”,escape=FALSE)%>%
可折叠样式(“条纹”,全宽=假)