【问题标题】:R Using kableExtra to colorize cells and maintain striped formatting with nested if/ifelse?R 使用 kableExtra 为单元格着色并使用嵌套的 if/ifelse 保持条纹格式?
【发布时间】:2019-03-02 22:10:27
【问题描述】:

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

我正在使用 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<.2>=.2)之间更改颜色?还是必须定义所有条件?

所需的输出:一个条带表,仅突出显示定义的值,允许条带存在于小于 0.10 的值上

【问题讨论】:

  • 注意,您的示例中不需要 mutate_if 行。之前的lapply 已经完成了该步骤
  • 已修复!完全忘记了。

标签: r kableextra


【解决方案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)

【讨论】:

  • 你是我的英雄。感谢您今天的帮助!
猜你喜欢
  • 2019-04-19
  • 2019-10-21
  • 2018-10-11
  • 1970-01-01
  • 2020-11-26
  • 2013-09-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多