word文档的R markdown flextable格式行

R markdown flextable formatting rows for word document

我正在使用 R markdown 和 flextable 创建一个 Word 文档,它希望包含如下所示的 table 但具有一些额外的格式。一般来说,我想将负数格式化为红色,这已经通过使用 color() 函数完成了。但是,我找不到将最后两行格式化为百分比的方法。我试过 formattable package 但没有成功。有人可以提供一些建议吗?非常感谢!

数据:

structure(list(X25th.percentile = c(3.01462950348061, -0.349849435071161, 
0.25), X50th.percentile = c(4.1590809972998, -0.103031116474755, 
0.5), X75th.percentile = c(5.71021088599362, 0.231493564666972, 
0.75)), class = c("formattable", "data.frame"), row.names = c(NA, 
-3L), formattable = list(formatter = "format_table", format = list(
    list(area(col = 1:3) ~ function(x) percent(x, digits = 0))), 
    preproc = NULL, postproc = NULL))

  flextable(tbl)%>%
colformat_double(i=1,digit=2 )%>%
color(i=~ X25th.percentile<0, j="X25th.percentile", color="red")%>%
color(i=~X50th.percentile<0, j="X50th.percentile", color="red")%>%
color(i=~X75th.percentile<0, j="X75th.percentile", color="red")

您可以稍微重构您的代码并使用 ifelse:

  tbl %>% 
    mutate(across(everything(), ~ifelse(. < 1, paste0(. * 100, "%"), .))) %>% 
    flextable() %>% 
    colformat_double(i=1,digit=2 )%>%
    color(i=~ X25th.percentile<0, j="X25th.percentile", color="red")%>%
    color(i=~X50th.percentile<0, j="X50th.percentile", color="red")%>%
    color(i=~X75th.percentile<0, j="X75th.percentile", color="red")

这给出:

不确定您的 use-case 是多少,但您可能还需要考虑四舍五入:

  tbl %>% 
    mutate(across(everything(), ~round(., 2))) %>% 
    mutate(across(everything(), ~ifelse(. < 1, paste0(. * 100, "%"), .))) %>% 
    flextable() %>% 
    colformat_double(i=1,digit=2 )%>%
    color(i=~ X25th.percentile<0, j="X25th.percentile", color="red")%>%
    color(i=~X50th.percentile<0, j="X50th.percentile", color="red")%>%
    color(i=~X75th.percentile<0, j="X75th.percentile", color="red")

类似,也可以使用colformat_double的后缀参数加上%符号:

tbl |>
  mutate(across(.fns = \(x) replace(x, 2:3, 100*x[2:3]))) |>
  flextable() |>
  colformat_double(i=1,digits=2 ) |>
  color(i=~ X25th.percentile<0, j="X25th.percentile", 
        color="red") |>
  color(i=~X50th.percentile<0, j="X50th.percentile", 
        color="red") |>
  color(i=~X75th.percentile<0, j="X75th.percentile", 
        color="red") |>
  colformat_double(i=2:3, suffix='%', digits = 4)