我使用包formattable
生成格式化表。我找到了一个很好的资源Formatting tables in R。但这里箭头格式的示例仅基于特定列。
我的要求是:假设我有来自不同城市的A列和B列,其中A的因子有两个级别'树木数'和'污染',而B是这些同比的百分比变化。因此,如果A列值增加为“树木数量”(因为它是正数),我希望用正绿色箭头格式化B列,如果减少则为红色,而对于污染则为反向。
所以从链接本身中获取示例(信用: Markus Gesmann ),即使对于IBM,即使更改<0,我也要显示一个正绿色箭头。< / p>
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)))
)
答案 0 :(得分:10)
基于?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
)。