我想基于不同的值集将不同的颜色着色应用于表。我正在使用kableExtra在Rmarkdown中创建此表。我希望0和<.10之间的值保持不变。值> =。10和<.20为黄色阴影。和值> =。20为阴影红色。
df
name category 1 categry 2 category a category b
ab .01 .45 .19 .09
410 .12 .01 .05 .66
NW 5th .25 .22 .01 .16
这就是我用现有表格制作的表格:
library(knitr)
library(dplyr)
kable(df, caption = "warning values", digits = 2, format = "latex",
booktabs = T)%>%
kable_styling(latex_options = c("striped"))%>%
landscape()%>%
row_spec(0, angle = 45)
我不确定如何使用mutate和cel_spec函数来应用于整个表。表列和行名称随每个报告fyi动态变化。
编辑:马丁的答案非常好。直到我试图清理我的号码。我的实际输入文件有更多数字,如Martin的答案。它还有包含下划线的文件和行名称。 (这在使用此答案时引起了问题,但我找到了解决方法。)
#replace any "_" with escaped "\\_" for magrittR/latex compatability
names(df) <- gsub(x = names(df), pattern = "\\_", replacement =
"\\\\_")
df$name <- gsub('\\_', '\\\\_', df$name)
#format numbers
df <- format(df, digits=0, nsmall=3, scientific = FALSE)
替换工作正常,它的数字格式打破了答案。一切仍然执行得很好,但我失去了彩色表。思考?
这是做到这一点的方法。请注意,我使用了magrittr中的复合赋值运算符。
---
title: test
output: pdf_document
---
```{r, echo = F, warning = F, message = F}
library(knitr)
library(dplyr)
library(kableExtra)
library(magrittr)
df <- data.frame(A = runif(4, 0, 1), B = runif(4, 0, 1), row.names = letters[1:4])
paint <- function(x) { # our painting function
ifelse(x < 0.1, "white", ifelse(x < 0.2, "yellow", "red"))
}
df %<>%. # compound assignment operator
mutate_if(is.numeric, function(x) { # conditional mutation, if the column type is numeric
cell_spec(x, background = paint(x), format = "latex")
})
kable(df, caption = "warning values", digits = 2, format = "latex",
booktabs = T, escape = F) %>%
landscape()%>%
row_spec(0, angle = 45)
```