Home > Software engineering >  Set the alignment of columns based on their data type using gt package
Set the alignment of columns based on their data type using gt package

Time:11-30

Given a data sample and gt code to plot table below:

df <- structure(list(category = c("food", "food", "food", "food", "electronic product", 
"electronic product", "electronic product", "electronic product"
), type = c("vegetable", "vegetable", "fruit", "fruit", "computer", 
"computer", "other", "other"), variable = c("cabbage", "radish", 
"apple", "pear", "monitor", "mouse", "camera", "calculator"), 
    price = c(6, 5, 3, 2.9, 2000, 10, 600, 35), quantity = c(2L, 
    4L, 5L, 10L, 1L, 3L, NA, 1L)), class = "data.frame", row.names = c(NA, 
-8L))

To plot:

dt <- df %>% 
  group_by(category) %>%
  gt() %>% 
  tab_header(
    title = md("Category name")
  )%>%
     tab_style(
     locations = cells_column_labels(columns = everything()),
     style     = list(
       #Give a thick border below
       cell_borders(sides = "bottom", weight = px(3)),
       #Make text bold
       cell_text(weight = "bold")
     )
   ) %>%
     tab_style(
     locations = cells_row_groups(groups = everything()),
     style     = list(
       cell_text(weight = "bold")
     )
   ) %>%
  cols_align(align = "center", columns = everything())
dt

Out:

enter image description here

Now I hope to custom cols_align() to align columns type, variable, price and quantity based on their datatype, if the datatype is character using center, if is number then using left.

How could I modify the code achieve that? Thanks.

CodePudding user response:

cols_align() accepts tidyselect semantics, so you can use:

library(dplyr)
library(gt)

df %>% 
  group_by(category) %>%
  gt() %>% 
  tab_header(
    title = md("Category name")
  )%>%
  tab_style(
    locations = cells_column_labels(columns = everything()),
    style     = list(
      #Give a thick border below
      cell_borders(sides = "bottom", weight = px(3)),
      #Make text bold
      cell_text(weight = "bold")
    )
  ) %>%
  tab_style(
    locations = cells_row_groups(groups = everything()),
    style     = list(
      cell_text(weight = "bold")
    )
  ) %>%
  cols_align(align = "center", columns = where(is.character)) %>%
  cols_align(align = "left", columns = where(is.numeric))
  •  Tags:  
  • r gt
  • Related