Colouring dataframe in Rstudio if values are equal to a previous column

Viewed 25

enter image description here

Hi,

i have a dataframe with an indicator column and i would like to colour the dataframe, so that if any values equal to the value in that specific row from the indicator column, gets coloured. (example in the picture above)

1 Answers

The View() function is not meant to allow for any kind of formatting, but you can use other tools, like knitr::kable() and functions from kableExtra.

library(dplyr)
library(knitr)
library(kableExtra)

df <- data.frame(indicator = rep(1, 5),
                 b2 = rep(3, 5),
                 b3 = rep(1, 5), 
                 b4 = rep(3, 5), 
                 b5 = rep(1, 5))

df |> 
  mutate(across(starts_with("b"), ~ cell_spec(.x, background = ifelse(.x == indicator, "red", "white"), color = ifelse(.x == indicator, "white", "black")))) |>
  kable(escape = FALSE) |> 
  kable_styling()

enter image description here

Related