使用 gt 包根据列的数据类型设置列的对齐方式

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

给定一个数据样本和 gt 代码来绘制下面的 table:

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))

绘制:

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

输出:

现在我希望自定义 cols_align() 以根据数据类型对齐列 typevariablepricequantity,如果数据类型是使用 center 的字符,如果是数字则使用 left.

我如何修改代码来实现?谢谢。

cols_align() 接受 tidyselect 语义,所以你可以使用:

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))