ř使用kableExtra上色细胞和维持与嵌套如果条纹格式化/ ifelse?(R Using ka

2019-10-30 04:33发布

对这个问题的扩展: - [R想从csv文件限制的数字的数量

我使用kableExtra和cell_spec上色嵌套ifelse语句细胞。

相反着色值小于0.10的白色的,我要离开他们独自为了让kableExtra应用条纹格式。

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

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 <0.2)和红色(> = 2)? 还是所有条件必须定义?

期望的输出:一个条纹表所限定,仅突出显示的值,从而允许条纹少的值存在比0.10

Answer 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)


文章来源: R Using kableExtra to colorize cells and maintain striped formatting with nested if/ifelse?
标签: r kableextra