R Using kableExtra to colorize cells and maintain striped formatting with nested if/ifelse?

穿精又带淫゛_ 提交于 2020-01-06 08:09:22

问题


An expansion to this question: R wanting to limit the amount of digits from csv file

I am using kableExtra and cell_spec to colorize cells with nested ifelse statements.

Instead of colorizing values less than .10 white, I want to leave them alone in order to allow kableExtra to apply the striped formatting.

I have a feeling this isn't possible though because of how the background colors are applied?

DF:

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

Code:

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)

Problem area?

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

can this be changed to only change the color if between yellow(>=.10<.2) and red(>=.2)? Or do all conditions have to be defined?

Desired output: a striped table that only highlights values as defined, allowing the stripes to exist on values less than .10


回答1:


You don't need to apply any formatting to the cells you wish to leave alone. So just test for that condition before calling cell_spec (i.e., only call cell_spec for those cells you want to format):

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)


来源:https://stackoverflow.com/questions/54963523/r-using-kableextra-to-colorize-cells-and-maintain-striped-formatting-with-nested

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!