Rachel Zhang
Rachel Zhang

Reputation: 564

R: conditional highlighting kable

Suppose I have a matrix like this:

set.seed(1234)
x = rnorm(10, mean=0, sd=1)
y = rnorm(10, mean=0, sd=1)
z = rnorm(10, mean=0, sd=1)
data=data.frame(rbind(x,y,z))

Is there any way I can highlight all certain cells (e.g. >0 in this case) without specifying the column?

My expected results would be like this (only positive values are highlighted):

Example

In the real case, I have around 30 columns and it's exhausted if I try to column_spec each column one by one:

data %>%
  column_spec(X1, color = "red") %>%
  column_spec(X2, color = "red")

......

Thanks!

Upvotes: 3

Views: 6156

Answers (1)

Maurits Evers
Maurits Evers

Reputation: 50678

You can do the following

---
title: "Untitled"
output:
  html_document: default
---    

```{r warning=FALSE, message=FALSE, echo=FALSE}
set.seed(1234)
x = rnorm(10, mean=0, sd=1)
y = rnorm(10, mean=0, sd=1)
z = rnorm(10, mean=0, sd=1)
data=data.frame(rbind(x,y,z))

library(knitr)
library(kableExtra)
library(tidyverse)

data %>% 
    mutate_all(~cell_spec(.x, color = ifelse(.x < 0, "red"," black"))) %>%
    kable(escape = F) %>%
    kable_styling()
```

This produces

enter image description here


Update

Or to change text and background colour

---
title: "Untitled"
output:
  html_document: default
---


```{r warning=FALSE, message=FALSE, echo=FALSE}
set.seed(1234)
x = rnorm(10, mean=0, sd=1)
y = rnorm(10, mean=0, sd=1)
z = rnorm(10, mean=0, sd=1)
data=data.frame(rbind(x,y,z))

library(knitr)
library(kableExtra)
library(tidyverse)

data %>% 
    mutate_all(~cell_spec(
        .x, 
        color = ifelse(.x < 0, "white", "white"),
        background = ifelse(.x < 0, "red"," black"))) %>%
    kable(escape = F) %>%
    kable_styling()
```

enter image description here

Upvotes: 12

Related Questions