Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Set the alignment of columns based on their data type using gt package

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

>Solution :

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))
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading