anderwyang
anderwyang

Reputation: 2451

In R/formattable,the total cell finally show `<span style="front-weight: bold">total</span>`

In blow code , the total cell finally show <span style="front-weight: bold">total</span>, How to handle it and make it show text 'total' with whished font, Thanks!

library(tidyverse)
library(formattable)

df <- data.frame(category=c('a','b','total'),value=c(1,2,3))
formattable(df,list(
  area(row = 3) ~ formatter("span", style = x ~ style(front.weight = "bold")),
  category = formatter("span", style = x ~ ifelse(x != 'total', style(color = "red"),x))))

enter image description here

Upvotes: 1

Views: 211

Answers (1)

akrun
akrun

Reputation: 887951

We could create two formatter and pass it as

library(formattable)
format_cat <- formattable::formatter("span",
                      style = x ~ ifelse(x != 'total', 
                                style(color = "red"), style(font.weight = "bold"))
)
format_oth <- formattable::formatter("span",
              style = x ~ ifelse(seq_along(x) ==3, style(font.weight = "bold"), x)
                                     )


formattable(df,list(
     value = format_oth,
     category = format_cat))

-output

enter image description here


Or create a single function and loop over the column names, apply the function and pass it on to formattable

format_gen <- function(colnm) {
     formattable::formatter("span",
                                     style = x ~ {
                                       style_red <- style(color = "red")
                                       style_bold <- style(font.weight = "bold")
                                       
                                       if(colnm == "category") {
                                         ifelse(x != 'total', 
                                                style_red, style_bold)
                                         
                                       
                                       } else {
                                         ifelse(seq_along(x) == 3, style_bold, x)
                                         
                                       }
                                     }
                                       
                                     
                                     )
  
  
}

-testing

formattable(df, setNames(lapply(names(df), format_gen), names(df)))

-output

enter image description here

Upvotes: 2

Related Questions