Douwe
Douwe

Reputation: 122

Choosing individual colors for a cell in a table using kable

Is it possible to choose your own color for a cell when creating a table using kable. In the folowing code from the kable documentation, it shows how you can choose a spectrum (from a couple of options) of colors for a row or column, but I want 1 color for 1 cell. That I can export to a PDF, using knitr.

vs_dt <- iris[1:10, ]
vs_dt[5] <- cell_spec(vs_dt[[5]], color = "white", bold = T,
background = spec_color(1:10, end = 0.9, option = "D", direction = -1))
15
kbl(vs_dt, booktabs = T, escape = F, align = "c")

Thank you

Upvotes: 1

Views: 760

Answers (1)

John Manacup
John Manacup

Reputation: 314

If you would only need 1 color for 1 cell, you can specify the row and column of that cell to be modified.

vs_dt <- iris[1:10, ]

#needed as they are factors
vs_dt$Species <- as.character(vs_dt$Species)

#only the first entry of the Species column
vs_dt[1,5] <- cell_spec(vs_dt[1,5], color = "white", bold = T,
      background = "red")

# you can also change some of them excluding the cell.
vs_dt[2:10,5] <- cell_spec(vs_dt[2:10,5], bold = T)

kbl(vs_dt, booktabs = T, escape = F, align = "c")

Upvotes: 1

Related Questions