我想做的是根据值有条件地在r中格式化整个表,我目前正在尝试使用flextable:
#some data
SalesData<-data.frame(Appliance=c("Radio", "Laptop", "TV", "Fridge"), ThisYear=c(5,25,5,8), LastYear=c(6,20,5,8))
#use flextable to conditionally format the data so that anything in the ThisYear column more than 10 is light blue
library(flextable)
SalesData<-regulartable(SalesData)
SalesData<-bg(SalesData, i = ~ ThisYear >10,j= ~ ThisYear,bg = "light blue")
SalesData
我拥有的表可能很大,因此如何将其应用于整个表而不必为每个单独的列指定格式?
答案 0 :(得分:4)
还请检查 bg
函数的 examples。
从 flextable V0.6.5
开始,使用颜色映射可以很容易地实现条件格式,例如scales::col_*
functions。
这是上一个示例的另一种可能的解决方案:
library(flextable)
# Some data
SalesData <- data.frame(Appliance = c("Radio", "Laptop", "TV", "Fridge"),
ThisYear = c(5, 11, 5, 12),
LastYear = c(19, 20, 5, 8))
# List of columns to loop through
columns <- c("ThisYear","LastYear")
# Define colors and ranges
bg_picker <- scales::col_bin(
palette = c("white", "light blue"),
domain = c(0, 100), # min and max range can be also set dynamically
bins = c(0, 10, 20)) # as well as the bins
ftab <- regulartable(SalesData) %>%
bg(j = columns, bg = bg_picker)
# Show the table
ftab
答案 1 :(得分:1)