3

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!

Rachel Zhang
  • 562
  • 6
  • 20

1 Answers1

11

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

Maurits Evers
  • 49,617
  • 4
  • 47
  • 68
  • Thank you so much Maurits! One last follow up question: is it possible to change the cell color (like the background color) instead of the text color? – Rachel Zhang Jul 25 '18 at 13:11
  • @RachelZhang Sure, you can change the background colour through `cell_spec` argument `background`; I've updated my answer to show an example. Please take a look. – Maurits Evers Jul 25 '18 at 13:25