我想基于不同的值集对表应用不同的颜色底纹。我正在使用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)
替换工作正常,其数字格式破坏了答案。一切仍然可以正常执行,但是我丢失了彩色表。 有想法吗?
答案 0 :(得分:1)
这是执行此操作的方法。注意,我使用了magrittr的compund赋值运算符。
---
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)
```