Reputation: 837
I have the following table in R using the kableExtra
package. I'd like to conditionally format the last row in my table where I can change the background color of a cell to green if the value is positive, and red if its negative.
library(kableExtra)
library(tidyverse)
data <- structure(list(Category = c("ICE BoA 0-3 Yr", "ICE BoA 1-5 Yr",
"JP Morgan 1-10 Yr", "USD/ZAR"), `Global Financial Crisis` = c(0.32,
0.26, 0.29, 0.08), `Taper Tantrum` = c(0.31, 0.43, 0.43, 0.14
), `Covid Crisis` = c(0.12, 0.57, 0.52, 0.29), `Entire Reference Period` = c(0.31,
0.31, 0.22, -0.26)), row.names = c(NA, -4L), class = c("tbl_df",
"tbl", "data.frame"))
kable %>% kable(align = 'lcccc') %>%
kable_styling(font_size = 30) %>%
column_spec(1, bold = T) %>%
row_spec(0, col = 'white', background = '#7c3042')
If I were formatting a column, it would be simple to do this with a simple mutate
argument before putting my dataframe into kableExtra
. Any idea on how to do this for a specific row?
mutate(
`Column Name` = cell_spec(`Column Name`, color = ifelse(`Column Name` > 0, "white", "white"),
background = ifelse(`Column Name` > 0, "green", "red")))
TIA
Upvotes: 1
Views: 582
Reputation: 3325
Can be accomplished with cell_spec
and specifying escape=FALSE
in the creation of kable.
data=as.data.frame(data)
gr=ifelse(data[4,]>0, "green", "red")
for (c in 2:5) {
data[4,c]=cell_spec(data[4, c], background=gr[c])
}
data %>% kable(align = 'lcccc', escape=FALSE) %>%
kable_styling(font_size = 10) %>%
column_spec(1, bold = T) %>%
row_spec(0, col = 'white', background = '#7c3042')
Upvotes: 1