R使用kableExtra为单元格着色并使用嵌套if / ifelse来保持条带化格式吗?

时间:2019-03-02 22:10:27

标签: r kableextra

对此问题的扩展:R wanting to limit the amount of digits from csv file

我正在使用kableExtra和cell_spec通过嵌套的ifelse语句为单元格着色。

为了让kableExtra应用条带化格式,我不想将其着色小于.10白色,而是将它们单独保留。

我有种感觉,尽管这是不可能的,因为背景颜色是如何应用的?

DF:

DF <- data.frame(V1 = sample(letters,10,T), V2 = abs(rnorm(10)), V3 = abs(rnorm(10)))

代码:

library(magrittr)
library(kableExtra)
paint <- function(x) {
  ifelse(x < 0.1, "white", ifelse(x < 0.2, "yellow", "red"))
}

DF[, -1] = lapply(DF[, -1], formatC, format = 'f', flag='0', digits = 2)
DF[,-1] = lapply(DF[,-1], function(x) cell_spec(x, background = paint(x), format = "latex"))

DF %<>%
  mutate_if(is.numeric, function(x) {
   cell_spec(x, background = paint(x), format = "latex") 
  })

kable(DF, caption = "colorized table with striping", digits = 2, format = "latex", booktabs = T, escape = F, longtable = T)%>%
  kable_styling(latex_options = c("striped", "hold_position", "repeat_header", font_size = 6))%>%
  landscape()%>%
  row_spec(0, angle = 45)

问题区域?

paint <- function(x) {
      ifelse(x < 0.1, "white", ifelse(x < 0.2, "yellow", "red"))
    }

是否可以更改为仅在黄色(> =。10 <.2)和红色(> =。2)之间改变颜色?还是必须定义所有条件?

期望的输出:条带化表格,仅突出显示所定义的值,从而允许条带存在于小于.10的值上

1 个答案:

答案 0 :(得分:1)

您不需要对要保留的单元格应用任何格式。因此,只需在调用cell_spec之前测试一下该条件即可(即,仅对要格式化的单元格调用cell_spec):

paint <- function(x) ifelse(x < 0.2, "yellow", "red")

DF[,-1] = lapply(DF[,-1], formatC, format = 'f', digits = 2)
DF[,-1] = lapply(DF[,-1], function(x) 
  ifelse(x < 0.1, x, cell_spec(x, background = paint(x), format = "latex")))

kable(DF, caption = "Highlighted numbers near zero", 
  digits = 2, format = "latex", booktabs = T, escape = F, longtable = T) %>%
  kable_styling(latex_options = c("striped", "hold_position", 
    "repeat_header", font_size = 6)) %>%
  landscape() %>%
  row_spec(0, angle = 45)