在R中创建表格时,如何使kable和formattable协同工作?

时间:2019-12-19 16:52:55

标签: r kable formattable

kableExtra和formattable都具有出色的功能,我希望能够将它们都合并到我的表中。

以下是使用formattable格式化的表:

Health_status = c("Very good", "Good", "Fair", "Bad", "Very bad", "Not stated", "Total")
Number = c(1032169, 453975, 125502, 22095, 5019, 73528, 1712288)
Percent = c(60.3, 26.5, 7.3, 1.3, 0.3, 4.3, 100)
Change = c(37672, 15231, 6536, 1988, 525, 30315, 92267)
Percent_Change = c(3.8, 3.5, 5.5, 9.9, 11.7, 70.2, 5.7)
df <- data.frame(Health_status, Number, Percent, Change, Percent_Change)

df %>% 
  formattable(align = c("l", "r", "r", "r", "r"),
              list(Health_status = formatter("span", style = style(color = "grey")),
                   Change = color_bar("#71CA97")))

哪个生成此表:

enter image description here

我想添加其他我似乎无法使用formattable但可以使用kable的功能(例如表标题)。但是,当我包含一个kable包时,整个表丢失的是格式更改:

df %>% 
  formattable(align = c("l", "r", "r", "r", "r"),
              list(Health_status = formatter("span", style = style(color = "grey")),
                   Change = color_bar("#71CA97"))) %>% 
    kable(caption = "Table1")

enter image description here

是否有一种仅使用formattable包含表标题的方法? (我不认为有),如果没有,是否可以同时使用formattable和kable?

帮助表示赞赏。

1 个答案:

答案 0 :(得分:1)

使用kableExtraformattable找到了一个对here有用的示例。

library(formattable)
library(kableExtra)

df %>% 
  mutate(
    Change = color_bar("#71CA97")(Change),
    Health_status = cell_spec(Health_status, "html", color = "grey")
  ) %>%
  kable("html", escape = F, caption = "Table 1", align = c("l", "r", "r", "r", "r")) %>%
  kable_styling("hover", full_width = F) %>%
  column_spec(4, width = "3cm")

enter image description here