I want to typeset NA
values in my table in italic using kableExtra
. It is easy enough to do so with one column:
library(dplyr)
library(kableExtra)
## Randomly assign NAs
d <- mtcars[1:5, ]
rownames(d) <- NULL
set.seed(20240807)
idx <- cbind(sample(5, 12, TRUE), sample(11, 12, TRUE))
idx <- idx[!duplicated(idx), ]
d[idx] <- NA
kbl(d) %>%
column_spec(1, italic = is.na(d[, 1]))
If I want to do the same thing for all columns, I need either to be very verbose, or to fall back to Reduce
(or any other form of looping) :
kbl(d) %>%
column_spec(1, italic = is.na(d[, 1])) %>%
column_spec(2, italic = is.na(d[, 2])) %>%
column_spec(3, italic = is.na(d[, 3])) %>%
column_spec(4, italic = is.na(d[, 4])) %>%
column_spec(5, italic = is.na(d[, 5])) # [...]
## or
kbl(d) %>%
{
Reduce((tbl, idx)
column_spec(tbl, idx, italic = is.na(d[, idx])),
1:11, .)
}
So I was wondering whether that are basically my only options (looping or being verbose), or if there is a kableExtra
canonical way of doing this?