簡體   English   中英

在 R 中創建數據表時組合 formattable 和 kableExtra 時缺少符號

[英]Missing symbols when combining formattable and kableExtra when creating a data-table in R

我正在嘗試結合使用 R 包formattablekableExtra來創建數據表。 使用 formattable,我在數字 > 0 的特定列(“b”)中添加了一個綠色的豎起大拇指符號,這可以正確顯示。 然后我將我的表格傳遞給“kable”,這樣我就可以添加“懸停”功能,加寬第 1 列,並添加分組標題。 但是,雖然生成的數據表正確顯示“懸停”功能和正確的分組標題,但缺少綠色豎起大拇指功能(源自 formattable)。

這是一個最小的、可重現的示例:

library(formattable)
library(kableExtra)
library(dplyr)

labels <- c("A", "B", "C")

a <- c(0.22, 0.28, 0.23)
b <- c(890.53, 346.84, 1119.63)
c <- c(6.56, 5.70, 4.59)
d <- c(0.0048, -0.3194, -0.2720)
e <- c(-0.3212, 0.1280,  0.0755)
f <- c("-", "-", "-")

df <- tibble(labels,a,b,c,d,e,f)

customGreen = "#71CA97"

# function to assign a thumbs up to numbers > 0
custom_thumb <- formatter("span", style = x ~ style(font.weight = "bold", 
                                                     color = ifelse(x > 0, customGreen, ifelse(x < 0, customRed, "black"))), 
                                   x ~ icontext(ifelse(x > 0, "thumbs-up", ""), x)
)

# use formattable to add thumbs up symbols 
df_frmt <- formattable(df, align =c("l","c","c","c","c","c","c"), 
           list(`labels` = formatter("span"), 
           `b` = custom_thumb))

# pass the resulting table to kable for further edits
df_kbl <- kbl(df_frmt, escape = T) %>%
          kable_styling("hover", full_width = F) %>%
          column_spec(1, width = "5cm") %>%
          add_header_above(c(" "=2, "Group 1" = 2, "Group 2" = 2, " " = 1))
df_kbl

鑒於 hover 功能和分組頭運行良好,問題是否與 escaping html 有關? 我已經在 kable 編輯中嘗試了“escape=T”和“escape=F”,盡管沒有任何變化。 通過閱讀本網站的“與格式化表集成”部分,我知道這兩個包可以一起使用。 我不知道它是否相關,但我在 RStudio 內的 RMarkdown 文件中運行此代碼。 任何幫助表示贊賞!

按照您提到的鏈接,組合formattablekableExtra不是通過將 formattable 傳遞給kbl function 來完成的。
相反,您可以使用來自kableExtra的自定義(您的custom_thumb )或原始函數( color_barcolor_tile )並將它們集成到formattable語法中。

df %>% 
  mutate(b = custom_thumb(b)) %>%
  kable("html", escape = F, align = c("l","c","c","c","c","c","c")) %>%
  kable_styling("hover", full_width = F) %>%
  column_spec(1, width = "5cm") %>%
  add_header_above(c(" " = 2, "Group 1" = 2, "Group 2" = 2, " " = 1))

在此處輸入圖像描述

暫無
暫無

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

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