将color_bar(...)和percent(...)在R的formattable中结合使用

5
我正在尝试创建一个颜色条,其中的条是基于一组行值的百分比,即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列中看到绿色的条形图,同时也以百分比的形式呈现。目前百分比代码会覆盖掉条形图。


相同的问题,但似乎不影响编写此指南的人: https://www.displayr.com/formattable/?utm_referrer=https%3A%2F%2Fwww.google.com%2F - Phillip Black
1个回答

2

我使用了 tidyverse 来完成这个操作,它非常好用。实际上,这个操作有两个部分,具体取决于你需要什么:

百分数格式

假设你已经有一个变量,该变量的编码范围在 0 到 1 之间。让我们称其为 pct_var

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

在0和1之间进行比例缩放

这个解决方案来自于DisplayR博客文章,需要您编写一个相当简单的函数(在其他情境中可能不是非常有用)。

perc_scale = function(x) (x/1)

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

就是这样,希望对某些人有用。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接