Search code examples
rdplyrformattable

How to change output for N/A on tables using formattable package in R


I'm making a table using the formattable package, here is the table and the code I have.

DataName = h1

Image of data

customGreen0 = "#DeF7E9"
customGreen = "#71CA97"
customRed = "#ff7f7f"

improvement_formatter <- formatter("span", 
                                   style = x ~ style(font.weight = "bold", 
                                                     color = ifelse(x > 0, customGreen, ifelse(x < 0, customRed,"black"))), 
                                   x ~ icontext(ifelse(x<0, "arrow-up", "arrow-down"),x)
)


formattable(h1, align =c("l","c","c","c","c", "c", "c", "c","c", "c","c", "c"), list(
  `Totals` = formatter("span", style = ~ style(color = "grey",font.weight = "bold")), 
  `2011`= color_tile(customGreen, customGreen0),
  `2012`= color_tile(customGreen, customGreen0),
  `2013`= color_tile(customGreen, customGreen0),
  `2014`= color_tile(customGreen, customGreen0),
  `2015`= color_tile(customGreen, customGreen0),
  `2016`= color_tile(customGreen, customGreen0),
  `2017`= color_tile(customGreen, customGreen0),
  `2018`= color_tile(customGreen, customGreen0),
  `2019`= color_tile(customGreen, customGreen0),
  `Average` = color_tile(customRed, customRed),
  `Change Since 2011` = improvement_formatter
))

h1[3,12] = "N/A"

This is the output I am getting

enter image description here For row 3, column 12 I need this to be N/A but do not want it to be green or have a up/down arrow. Is it possible to turn black and/or have sideways arrow that signals that this data is not not available?


Solution

  • Here's an example where NA does not have any color or arrow. In creating the h1 data frame, I used percent and included NA as one of the values. Let me know if this is what you had in mind.

    library(formattable)
    
    h1 <- data.frame(
      Totals = c("a", "b", "c", "d"),
      Y2011 = c(1230, 779, 37, 1176),
      Average = c(830,347,25,1140),
      Change = percent(c(-.01,.67,NA,.02), digits = 0)
    )
    
    customGreen0 = "#DeF7E9"
    customGreen = "#71CA97"
    customRed = "#ff7f7f"
    
    improvement_formatter <- formatter("span", 
                                       style = x ~ style(font.weight = "bold", 
                                                         color = ifelse(x > 0, customGreen, ifelse(x < 0, customRed,"black"))), 
                                       x ~ icontext(ifelse(x < 0, "arrow-up", "arrow-down"), x)
    )
    
    formattable(h1, align =c("l", "c", "c", "c"), 
                list(
      `Totals` = formatter("span", style = ~ style(color = "grey",font.weight = "bold")), 
      `Y2011`= color_tile(customGreen, customGreen0),
      `Average` = color_tile(customRed, customRed),
      `Change` = improvement_formatter
    ))
    

    Note that I left in red arrow up, green down as you intended.

    formattable table