kableExtra with Formattable 格式化问题

kableExtra with Formattable formatting questions

下面的代码创建了一个小 table。 我不清楚如何进行这些更改:

1) 两个条之间的白色较少 space。使用 Inspect Element 我可以将 .table>tfoot>tr>td 中的填充从 8px 更改为 3px。这是正确的做法吗?如果是这样,我如何将适当的 css 添加到我的 R 脚本中?

2) 去除彩条的圆角。同样,检查元素显示,如果我为每个单元格更改 border_radius:0px 和 padding-right:0px,则会发生更改。但同样,这似乎不正确。

3) 如何更改带有横条的单元格中文本字体的颜色?


library(formattable)
library(kableExtra)
library(knitr)

fraction <- function(x, df) {
  x/df$count
}

df <- tibble (
  Type = c("A", "B", "C"),
  count = c(500, 350, 860),
  Decreasing = c(226, 103, 507),
  Increasing = c(300, 250, 350)
) 


mutate(df,
       Decreasing = color_bar(color = "lightgrey", fun = "fraction", df)(Decreasing),
       Increasing = color_bar(color = "lightgreen", fun = "fraction", df)(Increasing)
) %>% 
  select(Type, Decreasing, Increasing) %>% 

  kable("html", escape = "F", align = c("l", "r", "l")) %>% 
  kable_styling(bootstrap_options = c("striped", "hover", "responsive"), full_width = F, position = "float_left")

如果您不介意不同的包裹(我自己的):

library(tibble)
library(dplyr)
library(huxtable)
df <- tibble (
  Type = c("A", "B", "C"),
  count = c(500, 350, 860),
  Decreasing = c(226, 103, 507),
  Increasing = c(300, 250, 350)
) 

ht <- as_hux(df) 
ht %>% 
       select(Type, Decreasing, Increasing) %>% 
       set_all_padding('3px') %>% 
       set_text_color(everywhere, 2:3, "red") %>% 
       add_colnames()

不过,这不会让您看到彩条。 (嗯,也许我应该添加一个功能。)您可以通过...获得这些功能,例如:

my_color_bar <- color_bar(color = "lightgrey", fun = "fraction", df)

ht %>% 
  select(Type, Decreasing, Increasing) %>% 
  set_all_padding('3px') %>% 
  set_text_color(everywhere, 2:3, "red") %>% 
  set_escape_contents(everywhere, 2:3, TRUE) %>% 
  set_number_format(everywhere, 2:3, list(my_color_bar)) %>% 
  add_colnames()

color_bar 来自 formattable 包,但好消息是您可以定义自己的 color_bar 函数(只需在 R 控制台中键入 color_bar 即可你是color_bar的源代码然后你可以修改它)。它将解决您的问题 2 和 3。

color_bar2 <- function (color = "lightgray", fun = "proportion", ...) 
{
  fun <- match.fun(fun)
  formatter(
    "span", 
    style = function(x) style(
      display = "inline-block", 
      direction = "rtl", `border-radius` = "0px", `padding-right` = "2px", 
      `background-color` = csscolor(color), color = csscolor("red"),
      width = percent(fun(as.numeric(x), ...))))
}

mutate(df,
       Decreasing = color_bar2(color = "lightgrey", fun = "fraction", df)(Decreasing),
       Increasing = color_bar2(color = "lightgreen", fun = "fraction", df)(Increasing)
) %>% 
  select(Type, Decreasing, Increasing) %>% 

  kable("html", escape = "F", align = c("l", "r", "l")) %>% 
  kable_styling(bootstrap_options = c("striped", "hover", "responsive"), full_width = F, position = "float_left")

对于问题 1,如果您在 rmarkdown 中呈现 table,请查看此页面 https://rmarkdown.rstudio.com/html_document_format.html#custom_css 了解如何在 rmarkdown 中使用 custom_css。