Skip to content

Instantly share code, notes, and snippets.

@mrcaseb
Last active November 11, 2022 20:55
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mrcaseb/f0f85b48df7957c27c4205cafccbc5a2 to your computer and use it in GitHub Desktop.
Save mrcaseb/f0f85b48df7957c27c4205cafccbc5a2 to your computer and use it in GitHub Desktop.
A suggestion how to align a column in a gt table to the decimal separator without monospace fonts
library(magrittr)
df <- tibble::tibble(
var_a = c("a", "b", "c", "d"),
var_b = c(1.234, 12.34, 123.4, 1234)
)
num_to_html <- function(num, separator = ".") {
stringr::str_split_fixed(num, stringr::fixed(separator), n = 2) %>%
as.data.frame() %>%
dplyr::rename(integer = V1, decimal = V2) %>%
dplyr::mutate(
html_string = glue::glue(
'<span style=" display:inline-block; text-align:right; width:{max(nchar(integer))}ch"> {integer} </span>',
"{separator}",
'<span style=" display:inline-block; text-align:left; width:{max(nchar(decimal))}ch"> {decimal} </span>'
)
) %>%
dplyr::pull(html_string)
}
df %>%
dplyr::mutate(var_b_and_more_labeltext = purrr::map(num_to_html(var_b), gt::html)) %>%
gt::gt()
@mrcaseb
Copy link
Author

mrcaseb commented Jun 7, 2021

Output:
grafik

@mrcaseb
Copy link
Author

mrcaseb commented Jun 7, 2021

It works for same number of decimals of course. Compare to centered colum var_b
grafik

@jthomasmock
Copy link

Thanks @mrcaseb !

I used these ideas to refactor internals of gtExtras::fmt_pad_num()

https://jthomasmock.github.io/gtExtras/reference/fmt_pad_num.html

@mrcaseb
Copy link
Author

mrcaseb commented Nov 11, 2022

Thanks @mrcaseb !

I used these ideas to refactor internals of gtExtras::fmt_pad_num()

https://jthomasmock.github.io/gtExtras/reference/fmt_pad_num.html

Oh nice! I forgot this thing existed. gtExtras became so powerful, I love it.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment