根据奇数行或偶数行更改 color_bar 颜色,R table

Change color_bar color based on odd or even rows, R table

我目前有一个格式table table例如下面的例子:

library(data.table)
library(dplyr)
library(formattable)
library(tidyr)
customGreen0 = "#DeF7E9"
customGreen = "#71CA97"
customRed = "#ff7f7f"

austinData= fread('https://raw.githubusercontent.com/lgellis/MiscTutorial/master/Austin/Imagine_Austin_Indicators.csv', data.table=FALSE, header = TRUE, stringsAsFactors = FALSE)
attach(austinData)

i1 <- austinData %>%
  filter(`Indicator Name` %in% 
           c('Prevalence of Obesity', 'Prevalence of Tobacco Use', 
             'Prevalence of Cardiovascular Disease', 'Prevalence of Diabetes')) %>%
  select(c(`Indicator Name`, `2011`, `2012`, `2013`, `2014`, `2015`, `2016`)) %>%
  mutate (Average = round(rowMeans(
    cbind(`2011`, `2012`, `2013`, `2014`, `2015`, `2016`), na.rm=T),2), 
    `Improvement` = round((`2011`-`2016`)/`2011`*100,2))
i1

color_bar3 <- function (color = "#49CA69", fun = "proportion", ...)
{
  fun <- match.fun(fun)
  formatter("span", style = function(x) style(display = "inline-block",
                                              `border-radius` = "5px", `padding-left` = "3px",
                                              `background-color` = csscolor(color),
                                              width = percent(fun(as.numeric(gsub(",", "", x)), ...))))
}


formattable(i1, align =c("l","c","c","c","r", "c", "l", "l", "r"), list(
  `Indicator Name` = formatter("span", style = ~ style(color = "grey",font.weight = "bold")), 
  `2011`= color_tile(customGreen, customGreen0),
  `2012`= color_tile(customGreen, customGreen0),
  `2013`= color_tile(customGreen, customGreen0),
  `2014`= color_bar(customRed),
  `2015`= color_tile(customGreen, customGreen0),
  `2016`= color_bar(customGreen),
  `Average` = color_bar3(customRed)
))

有这个table:

我想做但没找到方法的是: 如您所见,“平均值”列使用的是淡红色....

仅当我位于第 2 行(烟草使用流行率)或第 4 行(糖尿病流行率)时,如何将平均列的条形颜色更改为蓝色?

换句话说,如果我在第 1 行和第 3 行,我希望平均条为红色;如果我在第 2 行和第 4 行,我希望平均条为蓝色。类似于以下内容:

谢谢!

我们可以在area

中使用row/col
formattable(i1, align =c("l","c","c","c","r", "c", "l", "l", "r"), list(
  `Indicator Name` = formatter("span", style = ~ style(color = "grey",font.weight = "bold")), 
  `2011`= color_tile(customGreen, customGreen0),
  `2012`= color_tile(customGreen, customGreen0),
  `2013`= color_tile(customGreen, customGreen0),
  `2014`= color_bar(customRed),
  `2015`= color_tile(customGreen, customGreen0),
  `2016`= color_bar(customGreen),
  area(row = c(1, 3), col = `Average`) ~ color_bar3(customRed),
  area(row = c(2, 4), col = `Average`) ~ color_bar3("lightblue")
))

-输出