我想按小数点对齐 gt 表中的列,但我也希望它们居中。那可能吗?好像两者不能同时做?
install.packages("librarian")
librarian::shelf(tidyverse, gt)
data <-
tibble(group = c(1:5),
type_1 = c(1200, 3000, 100, 3300, 5200),
long_label_type_2 = c(2000, 120, 1200, 350, 2300))
将所有列居中对齐。
data %>%
gt() %>%
cols_align(
columns = everything(),
align = "center") %>%
fmt_number(
columns = everything(),
decimals = 0)
按小数点对齐类型列。
data %>%
gt() %>%
cols_align(
columns = c(group),
align = "center") %>%
cols_align_decimal(columns = c(type_1, long_label_type_2)) %>%
fmt_number(
columns = everything(),
decimals = 0)
这是使用
formatC
和 courier new(或任何等宽字体)的解决方法:
library(tidyverse)
library(gt)
# Toy data
my_data <- tibble(
group = c(1:5),
type_1 = c(1200, 3000, 100, 3300, 5200),
long_label_type_2 = c(2000, 120, 1200, 350, 2300))
# Formatting with `formatC`
# └ All numbers as strings with the same length
my_data<- my_data %>%
mutate(across(
contains("type_"),
\(x) x %>%
formatC(digits = 0, big.mark = ",", format = "f") %>%
str_pad(width = max(str_length(.)), pad = " ")))
# The table
# └ The monospaced font ensures the alignment
my_gt_table <- my_data %>%
gt() %>%
cols_align(columns = everything(), align = "center") %>%
tab_style(
style = cell_text(font = "courier new", whitespace = "pre"),
locations = cells_body(columns = c(type_1, long_label_type_2) ))
# Output
my_gt_table
创建于 2024-05-07,使用 reprex v2.1.0
希望有帮助。