【问题标题】:Combining color_bar(...) and percent(...) in R formattable在 R 格式表中结合 color_bar(...) 和 percent(...)
【发布时间】:2020-05-08 06:05:44
【问题描述】:

我正在尝试创建一个 color_bar,其中条形基于行值子集的百分比,即 a1=(a1+b1)/2。但是,我还希望将数字格式化为百分比。

我试过谷歌搜索,但找不到其他人有类似问题。我怀疑可能有更好的方法可以更容易地做到这一点,但我想不通。

tempDf = data.frame(a=c(0.8,0.5), b=c(0.2,0.5),c=c(500,500)) # dummy data
formattable(tempDf,unlist(list(
  lapply(as.list(1:nrow(tempDf)), function(row) {
    list(
      area(row, 1:2) ~ color_bar('green', function(row) row/sum(row)), # creates the green bars which are based on the percentage a1=(a1+b1)/2
      area(row, 1:1) ~ function(x) percent(x, digits = 1) # formats the a row as percent *this overwrites the color bars*
      )
  })
)))

预期的输出是绿色条在 A 列中可见并且以百分比表示。目前百分比代码会覆盖条形。

【问题讨论】:

标签: r formattable


【解决方案1】:

我使用tidyverse 进行了此操作,但它的作用就像一个魅力。它实际上有两个部分,具体取决于您的需要:

百分比格式

这是假设您已经有一个编码在 0 和 1 之间的变量。我们就叫它pct_var吧。

tempDf %>%
    mutate(pct_var = color_bar(colour_to_use)(formattable::percent(pct_var))

在 0 和 1 之间缩放条形

此解决方案来自DisplayR blog post,需要您编写一个非常简单的函数(在其他情况下可能不是很有用)。

perc_scale = function(x) (x/1)

tempDf %>%
    mutate(pct_var = color_bar(colour_to_use, fun = perc_scale)(formattable::percent(pct_var))

你有它,希望它对某人有用。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-05-21
    • 1970-01-01
    • 2011-01-29
    • 1970-01-01
    • 1970-01-01
    • 2021-08-09
    • 1970-01-01
    相关资源
    最近更新 更多