有条件的格式,带有“ kable”,但带有“%”号

时间:2019-03-13 15:22:04

标签: r formatting kable kableextra

我喜欢kablekableExtra包,用于表的条件格式设置,并在报表中使用它们。但是,我看到,如果您还想在表中包括“%”符号,则无法有条件地格式化表。有办法解决这个问题吗?

3 个答案:

答案 0 :(得分:1)

创建表时,您可以使用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)
```

结果:

Leads to this output

答案 1 :(得分:1)

@ 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)

答案 2 :(得分:0)

不知道您是否仍然坚持此方法,但是在处理同一问题时遇到了这个问题,因此决定发布我的解决方法。关键是要通过调色板函数(在本例中为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()
```
相关问题