YYY
YYY

Reputation: 89

How to change text colour of single cell in Kable Extra?

Is there a way of changing the text colour of a single cell/multiple cells?

For example, I have a table that I changed the colour of all text to red. But I want the diagonal colour to be blue

Is there a way to achieve this?

I have tried to use testStats[1, 2] <- cell_spec(testStats[1, 2], "latex", color = "blue") to change colour for one cell.

But doesn't seem to work.

library(kaleExtra)

test = iris
testStats = as.data.frame(apply(iris[,1:4], 2, summary))

kable(testStats, booktabs =TRUE,caption = "Sample") %>%
  kable_styling(latex_options = c('hold_position')) %>%
  column_spec(2:5, color = "red")


  testStats[1, 2] <- cell_spec(testStats[1, 2], "latex", color = "blue")

Upvotes: 2

Views: 1510

Answers (1)

Ronak Shah
Ronak Shah

Reputation: 388982

You can use cell_spec in a loop to change multiple cells. For diagonals you can do -

library(kableExtra)

test = iris
testStats = as.data.frame(round(apply(iris[,1:4], 2, summary), 2))
for(i in seq_along(testStats)) {
  testStats[i, i] <- cell_spec(testStats[i, i], "html", color = "blue")
}

kable(testStats, 'html', booktabs =TRUE,caption = "Sample", escape = FALSE) %>%
  kable_styling(latex_options = c('hold_position')) %>%
  column_spec(2:5, color = "red")

enter image description here

Upvotes: 3

Related Questions