簡體   English   中英

RMarkdown:Kable每行顏色最大百分比?

[英]RMarkdown: Color largest percentage in each row of Kable?

RMarkdown 如何正確着色 Kable 每一行中最大的百分比? 下面的代碼錯誤地 colors 單元格基於百分比的第一個數字的降序。 提前致謝: 代碼:

---
title: "Color Max Percentage"
output:
  html_document: default
  pdf_document: default
---

```{r setup, include = F}
library(tidyverse)
library(knitr)
library(kableExtra)
options(knitr.table.format = "html")

df = data.frame(
  x = c(1, 2, 3, 4, 5),
  a = c("12.7%", "14.0%", "49.2%", "20.4%", "23.2%"),
  b = c("35.6%", "19.0%", "9.1%", "25.5%", "11.2%"),
  c = c("6.9%", "54.1%", "31.3%", "15.4%", "17.5%")
)

df <- df %>%
  # adorn_totals('row') %>% 
  rowwise() %>% 
  mutate(across(a:c,  ~cell_spec(.x, format = "html", 
                                 color = ifelse(.x == max(c_across(a:c)), "red",  "blue"))))
df %>%
  kable(escape = F) %>%
  kable_styling()
```

(不正確)output: 在此處輸入圖像描述

您正在嘗試獲取最大的字符向量(即c("12.7%", "35.6%", "6.9%") )和 R,

max(c("12.7%", "35.6%", "6.9%"))
#> [1] "6.9%"

?max?comparison

字符版本按字典順序排序,這取決於使用的語言環境的整理順序:“比較”的幫助提供了詳細信息。

字符串可以與不同的標記編碼進行比較(參見編碼):在比較之前它們被翻譯為 UTF-8。

sort(c("12.7%", "35.6%", "6.9%"), decreasing = TRUE)
#> [1] "6.9%"  "35.6%" "12.7%"

因此,我們需要在使用readr::parse_number()進行比較之前將它們轉換為數字,並使用百分比格式打印單元格值,我們可以使用 formattable formattable::percent() function。

---
title: "Color Max Percentage"
output:
  html_document: default
  pdf_document: default
---

```{r setup, include = F}
library(tidyverse)
library(knitr)
library(kableExtra)
options(knitr.table.format = "html")

df = data.frame(
  x = c(1, 2, 3, 4, 5),
  a = c("12.7%", "14.0%", "49.2%", "20.4%", "23.2%"),
  b = c("35.6%", "19.0%", "9.1%", "25.5%", "11.2%"),
  c = c("6.9%", "54.1%", "31.3%", "15.4%", "17.5%")
)

df <- df %>%
  # adorn_totals('row') %>%
  mutate(across(a:c, ~ readr::parse_number(.x) / 100)) %>%
  rowwise() %>%
  mutate(across(
    a:c,
    ~ cell_spec(
      formattable::percent(.x, digits = 1),
      format = "html",
      color = ifelse(.x == max(c_across(a:c)), "red", "blue")
    )
  ))

df %>%
  kable(escape = F) %>%
  kable_styling()

```

使用 KableExtra 在 Kable 表中正確着色的最大單元格


暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM