3

我正在使用该包formattable生成格式化表。我在 R 中找到了一个不错的资源格式化表。但是这里的箭头格式示例仅基于特定列。

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

因此,以链接本身为例(来源:Markus Gesmann),仅针对 IBM 而言,即使更改小于 0,我也想显示一个正面的绿色箭头。

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)))
)
4

1 回答 1

14

基于以下文档?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 ~公式样式限制您仅使用右侧的变量本身。您必须切换到~然后在右侧显式写入列名(而不是 as x)。

于 2016-06-14T21:08:15.507 回答