使用dplyr mutate在RMarkdown中为pdf添加可附加的阴影表?
我想根据不同的值集对表应用不同的颜色着色。我正在使用kableExtra在Rmarkdown中创建此表。我希望0到=.10到=.20之间的值用红色着色使用dplyr mutate在RMarkdown中为pdf添加可附加的阴影表?,r,dplyr,r-markdown,mutate,kableextra,R,Dplyr,R Markdown,Mutate,Kableextra,我想根据不同的值集对表应用不同的颜色着色。我正在使用kableExtra在Rmarkdown中创建此表。我希望0到=.10到=.20之间的值用红色着色 df name category 1 categry 2 category a category b ab .01 .45 .19 .09 410 .12 .01 .05
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动态变化
编辑:马丁的答案很有效。直到我试图清理我的号码。我的实际输入文件有更多的数字,就像马丁的答案一样。它还有包含下划线的文件名和行名。(使用此答案时会出现问题,但我找到了解决方法。)
#用转义的“\\\\”替换任何“\\\”以实现magrittR/latex兼容性
名称(df)下面是一种方法。注意,我使用了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)
```
---
标题:测试
输出:pdf\U文件
---
```{r,echo=F,warning=F,message=F}
图书馆(knitr)
图书馆(dplyr)
图书馆(kableExtra)
图书馆(magrittr)
df%
行规格(0,角度=45)
```
谢谢!这非常有效,但我确实进一步扩展了我的代码,并打破了这个答案。我对上面的问题进行了编辑以反映。我试图找出原因,但我没有看到我的df前/后编号格式有任何明显的差异。
---
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)
```