基于多列的格式化

Formattable based on multiple columns

我正在使用包 formattable 生成格式化的 table。我找到了一个不错的资源 Formatting tables in R。但此处箭头格式示例仅基于特定列。

我的要求是:假设我有来自不同城市的 A 列和 B 列,其中 A 具有两个级别 'Number of Trees' 和 'Pollution' 的因子,而 B 是这些 YoY 的百分比变化。因此,如果 A 列的值增加 'Number of Trees'(因为它是正值),我想用正绿色箭头格式化 B 列,如果污染减少,则用红色箭头格式化,而相反。

因此,以 link 本身为例(来源:Markus Gesmann),即使变化小于 0,我也想展示 IBM一个正面的绿色箭头反对它。

library(formattable)
DF <- data.frame(Ticker=c("", "", "", "IBM", "AAPL", "MSFT"),
             Name=c("Dow Jones", "S&P 500", "Technology", 
                    "IBM", "Apple", "Microsoft"),
             Value=accounting(c(15988.08, 1880.33, NA, 
                                130.00, 97.05, 50.99)),
             Change=percent(c(-0.0239, -0.0216, 0.021, 
                              -0.0219, -0.0248, -0.0399)))
DF
##   Ticker       Name     Value Change
## 1         Dow Jones 15,988.08 -2.39%
## 2           S&P 500  1,880.33 -2.16%
## 3        Technology        NA  2.10%
## 4    IBM        IBM    130.00 -2.19%
## 5   AAPL      Apple     97.05 -2.48%
## 6   MSFT  Microsoft     50.99 -3.99%
formattable(DF, list(
  Name=formatter(
    "span",
    style = x ~ ifelse(x == "Technology", 
                       style(font.weight = "bold"), NA)),
  Value = color_tile("white", "orange"),
  Change = formatter(
    "span",
    style = x ~ style(color = ifelse(x < 0 , "red", "green")),
    x ~ icontext(ifelse(x < 0, "arrow-down", "arrow-up"), x)))
)

基于 ?formatter 上的文档:

formattable(DF, list(
  Name=formatter(
    "span",
    style = x ~ ifelse(x == "Technology", 
                       style(font.weight = "bold"), NA)),
  Value = color_tile("white", "orange"),
  Change = formatter(
    "span",
    style = ~ style(color = ifelse(Change < 0 & Ticker != "IBM", "red", "green")),
    ~ icontext(ifelse(Change < 0 & Name != "IBM", "arrow-down", "arrow-up"), Change)))
)

显然,x ~ 公式样式限制您只能在右侧使用变量本身。您必须切换到 ~,然后在右侧明确写入列名称(而不是 x)。