hirshg
hirshg

Reputation: 155

Applying a formattable format to all columns at once

I want to convert a dataframe to a formattable table and add a custom format to each column. Is there a way to apply the format to all columns without calling them specifically? Here is some sample code expaining what I currently have:

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

I have several more columns, and their names sometimes change, so I need a way to not manually call each column.

Upvotes: 1

Views: 1186

Answers (1)

Peace Wang
Peace Wang

Reputation: 2419

Try to use lapply

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

Upvotes: 2

Related Questions