【问题标题】:Applying a formattable format to all columns at once一次将可格式化的格式应用于所有列
【发布时间】:2021-02-14 13:01:52
【问题描述】:

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

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

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

【问题讨论】:

    标签: r formattable


    【解决方案1】:

    尝试使用 lapply

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-07-19
      • 1970-01-01
      • 2013-11-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-03-24
      相关资源
      最近更新 更多