Mark the highest and lowest value of a column with kableExtra in R

Asked

Viewed 45 times

1

I am building a report in Rmarkdown and need to create a table with the data table below:

MEDIA <- data.frame(Questões = c("Questão 43", "Questão 44", "Questão 45", "Questão 46", "Questão 52", "Questão 53"), 
                    Média = c(5.03, 5.00, 5.06, 3.80, 4.22, 4.49))

To create the table, I use the package kable and I’m trying to use the package kableExtra to create a kind of conditional formatting. My idea is that the table paint only the highest value of green and the lowest of red, so I don’t use arrange() and change the order of the column Issues. I wrote the code below:

knitr::opts_chunk$set(echo = FALSE, warning = FALSE, message = FALSE, options(digits = 3))
MEDIA %>%
    kbl() %>%
    kable_paper(full_width = F) %>%
    column_spec(2, color = ifelse(max(MEDIA$Média), "green", "red"))

But the code returns me all the values in green. It is possible to do this formatting with kableExtra, or some other R package?

1 answer

2

To the ifelse function as intended, has to have a logical condition and has no. max(MEDIA$Média) is not being compared with the values of this vector.

How this is not even a logical value:

max(MEDIA$Média)
#[1] 5.06

Properly:

MEDIA$Média == max(MEDIA$Média)
#[1] FALSE FALSE  TRUE FALSE FALSE FALSE

The code goes like this.

library(kableExtra)

knitr::opts_chunk$set(echo = FALSE, warning = FALSE, message = FALSE, options(digits = 3))
MEDIA %>%
  kbl() %>%
  kable_paper(full_width = F) %>%
  column_spec(2, color = ifelse(MEDIA$Média == max(MEDIA$Média), "green", "red"))

inserir a descrição da imagem aqui

  • Thank you very much!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.