FlexTable 中整个 table 的条件格式

Conditional formatting of entire table in FlexTable

我想做的是根据一个值在 r 中有条件地格式化整个 table,我目前正在尝试使用 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

我拥有的 table 可能非常大,那么如何将其应用到整个 table 而不必为每个单独的列指定格式?

为此,您可以不使用 j,或者将其值设置为列名:

SalesData<-data.frame(Appliance=c("Radio", "Laptop", "TV", "Fridge"), ThisYear=c(5,25,5,8), LastYear=c(6,20,5,8))

# option 1
ft1 <-regulartable(SalesData)
ft1 <-bg(ft1, i = ~ ThisYear >10, bg = "light blue")
ft1

# option 2 (recommanded)
ft2 <-regulartable(SalesData)
ft2 <- bg(ft, i = ~ ThisYear >10, j = names(SalesData), bg = "light blue")
ft2

我想我会post这里的最终代码,因为它可能对某人有帮助: 代码围绕 'columns' 向量中指定的列循环,并根据其值对它们进行着色。

#some data 
SalesData<-data.frame(Appliance=c("Radio", "Laptop", "TV", "Fridge"), ThisYear=c(5,11,5,12), LastYear=c(19,20,5,8))

library(flextable)
SalesData<-regulartable(SalesData)

#list of columns to loop through
columns<-c("ThisYear","LastYear")

#loop to colorise the columns
for (i in seq_along(columns)){
#anything with a value of more than 10 is formatted light blue
eval(parse(text= paste0("SalesData<-", "bg (SalesData,i=~", columns[i], ">10, j=~", columns[i], " ,bg=\"light blue\")")))
}
#show the table
SalesData

请同时检查 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