Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

r

formattable

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.

like image 493
HankSkank Avatar asked Oct 28 '22 10:10

HankSkank


1 Answers

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.

like image 191
MokeEire Avatar answered Jan 11 '23 18:01

MokeEire