How to fill background using kableExtra with odd and even numbers

Hi, I would like help on how to fill background color using kableExtra. I would like to fill the background with the even numbers red and the odd numbers orange. Thank you.
table screenshot

Below is one way to fill odd/even columns using the which() function to identify which columns are odd or even and then the column_spec() function to apply the background color.

library(kableExtra)
library(tidyverse)

df = head(iris, 5)

odd_cols = which(1:ncol(df) %% 2 == 1)
even_cols = which(1:ncol(df) %% 2 == 0)

kbl(df) |>
  kable_paper(full_width = F) |>
  column_spec(odd_cols, background = 'orange') |>
  column_spec(even_cols, background = 'red')

image

Hi scottyd22,

Thank you for working this out for me.
It worked out great.

Rosario

This topic was automatically closed 42 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.