Combining color_bar(…) and percent(…) in R formattable

对着背影说爱祢 提交于 2020-08-27 08:32:10

问题


I'm trying to create a color_bar where the bars are based on the percentage of a subset of row values i.e. a1=(a1+b1)/2. However, I also want the numbers to be formatted as percent.

I have tried googling but can't find anyone else having a similar problem. I suspect there might be a better way of doing this that is easier but I can't figure it out.

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*
      )
  })
)))

Expected output is that the green bars are visible in the A column as well as being in percent. Currently the percent code overwrites the bars.


回答1:


I did this using the tidyverse, but it works like a charm. There's actually two portions to it, depending on what you need:

Percent formatting

This is assuming you have a variable which is coded between 0 and 1 already. Let's call it pct_var.

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

Scaling the bar between 0 and 1

This solution came from a DisplayR blog post and requires you to write a pretty simple function (likely not a very useful one in other contexts).

perc_scale = function(x) (x/1)

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

And there you have it, hope it's useful to someone.



来源:https://stackoverflow.com/questions/57275279/combining-color-bar-and-percent-in-r-formattable

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!