這個問題類似于我過去的問題:
我的問題是我希望將數字列印為百分比。我嘗試在條件格式之前和之后使用 scales::percent ,但它們都不起作用。如果我嘗試在粗體后給出百分比格式,則會收到錯誤訊息:
UseMethod(“round_any”)中的錯誤:沒有適用于“round_any”的方法應用于“字符”類的物件。
如果我嘗試在條件粗體之前使用它,那么我找不到每行的最大值,因為它們是字符而不是數字。
aux.n<- df
aux.n[c(3:ncol(aux.n))] = sapply(aux.n[c(3:ncol(aux.n))], function(x) scales::percent(x, accuracy = 0.1))
我應該補充一點,這只是一個示例,但實際數字類似于 0.5471927,因此列印“54.7%”而不是完整數字非常重要。
我使用的庫:
require("pacman")
p_load(tidyverse, reshape, reshape2, knitr, kableExtra, tinytex, scales, pander, janitor)
uj5u.com熱心網友回復:
百分比值使用 cell_spec 引數轉換為字符。使用一點stringr和正則運算式,十進制值可以轉換為百分比。注意 % 是 LaTeX 中的保留符號,因此需要轉義。
---
output:
pdf_document
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = FALSE)
require("pacman")
p_load(dplyr, tidyr, stringr, kableExtra, forcats, tinytex, scales, janitor)
```{r df, include=FALSE}
segment<- c('seg1', 'seg1', 'seg2', 'seg2', 'seg3', 'seg3', 'Tot')
subSegment<- c('subseg1.1', 'subseg1.2', 'subseg2.1', 'subseg2.2', 'subseg3.1', 'subseg3.2', "-")
co.1<- c(0.1, 0.4, 0.3, 0.2, 0.5, 0.4, 0.4)
co.2<- c(0.5, 0.3, 0.3, 0.2, 0.1, 0.5, 0.4)
co.3<- c(0.2, 0.1, 0.4, 0.4, 0.1, 0.1, 0.15)
co.4<- c(0.2, 0.2, 0.0, 0.2, 0.3, 0.0, 0.05)
total<- c(1,1,1,1,1,1,1)
df <-
data.frame(segment, subSegment, co.1, co.2, co.3, co.4, total) %>%
rowwise() %>%
mutate(across(co.1:co.4, ~cell_spec(.x, 'latex', bold = ifelse(.x == max(c_across(co.1:co.4)), TRUE, FALSE)))) %>%
ungroup() %>%
pivot_longer(starts_with("co."))%>%
mutate(pc = percent(as.numeric(str_extract(value, "0.\\d |0")), accuracy = 0.1),
value = str_replace(value, "0.\\d |0", pc),
value = str_replace(value, "%", "\\\\%")) %>%
select(-pc) %>%
pivot_wider() %>%
select(-total, everything(), total)
```
```{r kable, results='asis'}
df %>%
kable(booktabs = TRUE,
caption = "Title",
align = "c",
escape = FALSE) %>%
kable_styling(latex_options = c("HOLD_position", "repeat_header", "scale_down"),
font_size = 6) %>%
pack_rows(index = table(fct_inorder(df$segment)),
italic = FALSE,
bold = FALSE,
underline = TRUE,
latex_gap_space = "1em",
background = "#f2f2f2") %>%
column_spec(1, monospace = TRUE, color = "white") %>%
row_spec(nrow(df), bold = TRUE)
```

轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/447069.html
標籤:数据框 pdf r-降价 卡布尔 kableextra
上一篇:使用Python在后臺使用AcrobatReader打開和保存PDF檔案
下一篇:簽名后無法保存pdf
