Last active
November 11, 2022 20:55
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Oh nice! I forgot this thing existed. gtExtras became so powerful, I love it.