Search code examples
rformattable

R: (Formattable) Is there a way to make color_bar with condition?


I'm trying to make "yes" in green color bar "no" in red color bar.. but with the code below only turn the words into green/red.. i tried doing x ~ formattable::style(color_bar = ifelse(x == "yes", "green" but it does not work that way..

YesNo = formattable::color_bar("red") with this code I get this output.. but i'm trying to get "yes" in green and "no" in red.. Something like this but turn "yes" into green and "no" to red..

df = data.frame(YesNo = c("yes","no","yes","no"), 
            Numbers = c(4, 5, 10, 10))
df

rownames(df) = c("Test1","Test2","Test3","Test4")
df

formattable(df)

    
  sign_formatter <- formattable::formatter("span", 
                                          style = x ~ formattable::style(color = ifelse(x == "yes", "green", 
                                                                                        ifelse(x == "no", "red", "green"))))                                  

Solution

  • We could create a condition in background-color and pass that in formattable

    color_formatter <- formattable::formatter(
      "span",
      style = x ~ style(
        color = 'white',
        'background-color' =
          ifelse(x == "yes", "green", "red")
                ))
    formattable::formattable(df, list(
      YesNo = color_formatter,
      Numbers = formattable::color_tile("transparent","lightgreen")))
    

    -output

    enter image description here