Home > Software design >  Add a color column based on the values from other column
Add a color column based on the values from other column

Time:08-13

I am trying to add color to a column based on its values. I have a column named Class with two values instructor and student. I want to give a black color to the instructor and green color to student.

I have tried the following:

library(gt)
df <- df %>% 
  mutate(Class = ifelse(as.character(Class) == "instructor", "black", "green")) %>% 
  gt() %>%
  data_color(columns = Class,
             colors = scales::col_numeric(
      palette = c("black", "green"), domain = c(0.2E7, 0.4E7)
      ))

I am using the data_color() method from the gt() https://gt.rstudio.com/reference/data_color.html package but gives me the following error:

Error in UseMethod("rescale") : 
no applicable method for 'rescale' applied to an object of class "character"

data:

Class
-----
student
student
student
instructor
student
instructor
....

Is there a way that I can add a color value or put a color to a column in R?

CodePudding user response:

The following code should do it. Here I first find the columns that should be colored (using the which()-function) and then telling tab_style()the just found locations.

This link Set row color (Stackoverflow) might also help.

library(gt)
# example data
df<-data.frame(Class=c("student","student","student","instructor","student","instructor"))

## find positions of "instructor"
index1<-which(df$Class=="instructor")
## find positions of "student"
index2<-which(df$Class=="student")

df %>% gt() %>%
  tab_style(
    style=list(
      cell_fill(color="green")
    ),
    locations= cells_body(
      rows=index1
    )
  ) %>%
  tab_style(
    style=list(
      cell_fill(color="lightblue")
    ),
    locations= cells_body(
      rows=index2
    )
  )
  •  Tags:  
  • r gt
  • Related