rkableextra

How to Ignore NA in cell_spec() call with kableextra?


My question is similar to this previous post as I would like to conditionally format certain values while ignoring NA. I'm finding NA gets overwritten with the cell specifications following cell_spec(), and as a result, options(knitr.kable.NA = '') does not work. Can someone please assist? Example data is below.

library(tidyverse)
library(kableExtra)

df <- data.frame(
  name = paste("Name", LETTERS[1:10]),
  var1 = c(0.5, -1.3, NA, 3.4, -2.6, 0.8, NA, 0.3, 2, -1.6)
  )

df_fill <- df %>%
  mutate(var1 = cell_spec(
    var1,
    background = case_when(
      var1 >= 1 ~ "#FEDCDA",
      var1 <= -1 ~ "#E5F8E0",
      .default = "white")
    )
    )

options(knitr.kable.NA = '')

kbl(df_fill,
    booktabs = TRUE,
    escape = FALSE,
    linesep = "") %>%
  kable_styling(latex_options = c("HOLD_position"),
                font_size = 8)

Solution

  • Only apply cell_spec if your variable is not NA:

    df_fill <- df %>%
      mutate(var1 = case_when(!is.na(var1) ~ cell_spec(
        var1,
        background = case_when(var1 >= 1 ~ "#FEDCDA",
                               var1 <= -1 ~ "#E5F8E0",
                               .default = "white")
      )))
    

    enter image description here