[英]Conditional formatting with `kable` but with “%” signs
我喜歡kable
和kableExtra
包,用於表的條件格式設置,並在Reports中使用它們。 但是,我看到,如果您還想在表中包括“%”符號,則無法有條件地格式化表。 有辦法解決這個問題嗎?
您可以在創建表時使用scales::percent()
,如下所示:
---
title: "test"
output: word_document
---
```{r setup, include=FALSE}
library(tidyverse)
library(knitr)
library(scales)
df <- diamonds
tabl1 <- df %>% group_by( cut) %>% summarise(n = n())
names(tabl1) <- c("Count of Cut", "n")
tabl1$perc <- scales::percent(tabl1$n / sum(tabl1$n))
```
```{r , message= FALSE, echo=FALSE,warning=FALSE}
kable(tabl1)
```
結果:
@ heck1有一個很好的答案,我對該程序包一無所知。 將來,如果您包括樣本數據,您嘗試過的內容以及所需的結果,將會很有幫助。 根據您的評論,我認為您正在尋找類似以下的內容。 當然,您可以更改列名並進行其他您認為合適的修改。
---
title: "test"
output: word_document
---
```{r setup, include=FALSE}
library(tidyverse)
library(knitr)
library(kableExtra)
df <- diamonds
tabl1 <- df %>%
group_by(cut) %>%
summarise(n = n()) %>%
mutate(perc = round(n / sum(n), 3)*100,
cut = cell_spec(cut, color = ifelse(perc < 10, "red", "black")),
perc = paste0(perc, "%"))
```
```{r , message= FALSE, echo=FALSE,warning=FALSE}
kable(tabl1, escape = F) %>%
kable_styling(full_width = F)
不知道您是否仍在堅持,但在處理同一問題時遇到了這個問題,因此決定發布我的解決方法。 關鍵是要通過調色板函數(在本例中為spec_color)傳遞值的數字版本,同時使用帶有“%”字符的字符值作為cell_spec的輸入,以便將“%”包含在cell_spec返回
---
title: "R Notebook"
output:
html_document: default
pdf_document: default
---
```{r setup, include = F}
library(tidyverse)
library(knitr)
library(kableExtra)
options(knitr.table.format = "html")
```
```{r}
df = tibble(
x = c(1, 2, 3, 4, 5),
percents = c("12.7%", "14.0%", "19.2%", "20.4%", "13.2%")
)
```
```{r}
df = df %>%
mutate(percents = cell_spec(percents, format = "html",
#I first remove the "%" character,
#then coerce the column to a numerical value so that
#the color palette function can handle it
color = spec_color(as.numeric(str_sub(percents, end = -2L))))
)
df %>% kable(format = "html", escape = F) %>% kable_styling()
```
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.