How do I specify a column within a dplyr chain to define the condition to do conditional formatting?
I am looking to have different background colors in a kable depending on the cell value. Per the 2020-10-06 documentation for knitr:kable and kableExtra by Hao Zhu, I'm trying to define the colors using column_spec and an ifelse statement but the latter requires I explicitly name the column to state the condition:
mtcars[1:8, 1:8] %>%
arrange(wt) %>%
kbl(booktabs = T, linesep = "") %>%
kable_paper(full_width = F) %>%
column_spec(6, color = "white", background = ifelse(mtcars[1:8,1:8]$drat > 3, "red", "green"))
returns a formatting reflecting the original order of the dataframe, not the arranged one:
If I use . instead of referring to the dataframe by name:
mtcars[1:8, 1:8] %>%
arrange(wt) %>%
kbl(booktabs = T, linesep = "") %>%
kable_paper(full_width = F) %>%
column_spec(6, color = "white", background = ifelse(.$drat > 3, "red", "green"))
I get the error: Error in .$drat : $ operator is invalid for atomic vectors
. Removing .$
returns Error in ifelse(drat > 3, "red", "green") : object 'drat' not found.
How can I define the condition by referring to the internal dataframe derived through the dplyr chain?
Thanks.