gpt4 book ai didi

r - 在 R 格式表中组合 color_bar(...) 和 percent(...)

转载 作者:行者123 更新时间:2023-12-03 17:13:27 25 4
gpt4 key购买 nike

我正在尝试创建一个 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 列中可见并且以百分比表示。目前百分比代码会覆盖条形。

最佳答案

我使用 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))


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

关于r - 在 R 格式表中组合 color_bar(...) 和 percent(...),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57275279/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com