Home > Software engineering >  Colour coding p values in a gt table with no column names
Colour coding p values in a gt table with no column names

Time:01-25

I have the following gt table:

library(dplyr)
library(gt)
group1 <- c("0", "1", "10", "100", "1000")
group2 <- c("0", "1", "10", "100", "1000")
pvalue <- c("0.06", "0.042", "0.001", "1", "0.02")
data <- data.frame(group1, group2, pvalue)

data %>% 
  pivot_wider(names_from = group2,
              values_from = pvalue) %>%
  gt() %>%
  cols_label(group1 = "") %>% 
    sub_missing(
  columns = everything(),
  rows = everything(),
  missing_text = "") 

enter image description here

Is there a way to colour code p values that are less than 0.05 blue, and less than 0.01 red? I have tried the data_colours argument, but as I have no column names it isn't working.

CodePudding user response:

You were on the right track with using data_color. And of course do you have column names even if they are not really needed as we only have to exclude the first column:

library(dplyr)
library(tidyr)
library(gt)

data %>% 
  pivot_wider(names_from = group2,
              values_from = pvalue) %>%
  mutate(across(-1, as.numeric)) %>%
  gt() %>%
  cols_label(group1 = "") %>% 
  sub_missing(
    columns = everything(),
    rows = everything(),
    missing_text = "") %>%
  data_color(
    columns = -1,
    colors = scales::col_bin(
      palette = c("red", "blue", "transparent"),
      bins = c(0, 0.01, .05, 1),
      na.color = "transparent"
    )
  )

enter image description here

  • Related