Decimal aligning numeric columns in a gt table

Viewed 375

For presentation, sometimes numbers are required to be decimal aligned within their column in tables.

The cols_align() function in the gt package has only a centre, right or left option for aligning numbers.

library(tidyverse)
library(gt)

df <- tibble(left_aligned = c(1.22, 222),
       right_aligned = c(4300, 0.1223))

df_gt <- df %>% 
   gt() %>% 
  cols_align(columns = 1,
             align = "left") %>% 
  cols_align(columns = 2,
             align = "right") %>% 
  fmt_number(columns = 1,   # Format the numbers so they display the correct number of decimals
             rows = 1,
             decimals = 2) %>% 
  fmt_number(columns = 1,
             rows = 2,
             decimals = 0) %>% 
  fmt_number(columns = 2,
             rows = 1,
             decimals = 0) %>% 
  fmt_number(columns = 2,
             rows = 2,
             decimals = 4)

df_gt

enter image description here

Is there the ability to align the column by the decimal point instead?

So that it looked similar to this:

enter image description here

1 Answers

With new extention to this package gtExtras - you can do it.

Using example from the question:

library(gt)
library(gtExtras)

df <- data.frame(left_aligned = c(1.22, 222),
                 right_aligned = c(4300, 0.1223)) 
gt(df) %>%
    fmt_pad_num(columns = c(left_aligned, right_aligned))

Output:

enter image description here

Related