首页 > 解决方案 > 一次将可格式化的格式应用于所有列

问题描述

我想将数据框转换为可格式化的表格,并为每一列添加自定义格式。有没有办法将格式应用于所有列而不专门调用它们?这是一些示例代码,说明了我目前拥有的内容:

library(formattable)    

# create df
col1 <- c(0, -2, 4)
col2 <- c(-1, 0, 2)
col3 <- c(-1, -1, 0)
df <- data.frame(col1, col2, col3)

# set colors
red <- "#ff7f7f"
blue <- "#7f9dff"
white <- "#ffffff"

# add custom format
color_format <- formatter('span', 
                          style = x ~ style(color = ifelse(x > 0, blue, 
                                                           ifelse(x < 0, red, white))))

# create table
formattable(df, 
            list("col1" = color_format,
                 "col2" = color_format,
                 "col3" = color_format))

我还有几列,它们的名称有时会改变,所以我需要一种不手动调用每一列的方法。

标签: rformattable

解决方案


尝试使用lapply

myForm <- function(x) {
              formatter('span',
                        style = x ~ style(
                          color = ifelse(x > 0, blue,
                                         ifelse(x < 0, red, white))
                        ))
}
formattable(df, lapply(df, myForm))

推荐阅读