gt::fmt_number() changes font style to italic

Hello,

I have encountered some weird issues regarding formatting numbers in a gt::gt() object, which is knitted to pdf via tinytex and quarto. See this little example:

---
title: "Reprex"
format:
  pdf:
    mainfont: Arial
    sansfont: Times New Roman
---

## A Header in Times New Roman

\```{r}
#| label: theIssue

mtcars[,1:3] |>
  head(6) |>
  gt::gt() |>
  gt::fmt_number(columns = 1, decimals = 3) |>
  gt::tab_options(table.font.size = gt::px(6))
\```

Normal text in Arial.

If I look at the output, the non formatted numbers are in standard Arial, while the formatted numbers are in italic style. A closer look on the raw .tex file reveals, that the formatted numbers are converted to math mode - they all are encapsulated in $.

Is there anybody who can guide me into the right direction, how to force gt to not encapsulate the formatted numbers in math mode but instead just show them in a formatted fashion? Should I transform all numbers to characters beforehand and see if it works (the main issue is, that the number of decimals in my "real" table is different between rows - e.g. the rows in a column are alternating between integers (no decimal needed) and percentages (one digit needed)).

Thanks in advance and kind regards

On the italics issue, this might be an artifact of tinytex, because with xelatex I don't see it with this forematter


title: "Reprex"
format: pdf
mainfont: Lato
monofont: Roboto

(I don't have either Ariel or Times New Roman installed)

For the alternating rows, the default is gt(... rows = everything()) but you can provide a vector of row indices to make odd and even rows format differently with two fmt_number() calls.

1 Like

The alternating rows are already done, I just wanted to emphasize that this is the reason why I needed fmt_number() in the first place.

I am just curious, why gt transforms numbers into math mode. Because it really looks ugly this way and out of sync with the rest (of the table and the plain text).

I also looked at the transformation of just even rows and compared it to unchanged odd rows - the transformed are in math mode, the odd rows in normal text .

Is there anything I can do to prevent this behavior? I mean I could output the .Tex table and manually change everything from math mode to normal, but that would be really annoying for 14 tables or so....

Quarto has a lot of power and a lot of moving parts—ultimately ending up in pandoc before being dispatched to a pdf engine. It's hard to know without digging deeply where the switch is turned to produce math mode.

I wonder if mainfont works only with the regular pdf engines, xelatex and associated. See this S/O, stating that the fontfamily option specifically requires the pdflatex. You might consider doing a full T_eX install.

1 Like

Hm, not sure here - the knitting states at least that it uses Xetex and changing the mainfont option in YAML also effects the font on the plain text. So this is working at the very least.

I will try to Change my engine and see if it reaolves the issue, but since the table saved with gt_save() already contains the "wrongly" formatted numbers, I suspect that there is somethin at the level of gt going on I miss here.

Specifying pdf-engine: xelatex in the YAML-header changed the output of formatted numbers from math mode to normal text. Without this specification, the math mode persists.

Thanks for the suggestion to set the pdf-engine in the YAML header! :slight_smile:

Okay, never mind. I just changed the main and sans font to Source Sans Pro to compare the results and now it is again obviously another font family that is used here (I guess Calibri Math is the default for math syntax?).

So back to the beginning... Damn it.

@technocrat This is the full setting of specifications I have (excluding some .tex files I also load, but those just affect the appearance of a title page and the bibliography).

---
title: "Reprex"
format:
  pdf:
    documentclass: article
    classoption: a4paper
    number-sections: true
    fig-align: left
    fig-pos: 'h'
    tbl-cap-location: top
    fig-height: 4.3
    fig-width: 6.1
    fontsize: "12pt"
    pdf-engine: xelatex
    mainfont: Arial
    sansfont: Arial
    include-in-header: 
      text: |
        \usepackage{lipsum}
---

## A Header

\```{r}
#| label: theIssue
#| echo: false

library(gt)

my_table <- data.frame(var = rep(c("count","share"), 2),
                       group = rep(c("male","femal"),each = 2),
                       value_formatted = c(850,42.5,1150,57.5),
                       value_unformatted = c(850,42.5,1150,57.5))

my_table |>
  gt(
      groupname_col = 'group',
      rowname_col = 'var'
    ) |>
  fmt_number(columns = 3, rows = c(1,3), locale = 'de_DE', decimals = 0) |>
  fmt_number(columns = 3, rows = c(2,4), locale = 'de_DE', decimals = 2) |>
  tab_spanner(label = "A Spanner", columns = 3: 4) |>
  cols_label(.list = c('var' = '','group' = '','value_formatted' = 'value_formatted','value_unformatted' = 'value_unformatted')) |>
   tab_footnote(
      footnote = "I also have a footnote",
      locations = cells_column_spanners(spanners = 1)
    ) 
\```

\lipsum[5]

The output looks like this:

The text and unformatted numbers are in the correct font family, the formatted numbers are in math mode with another font family which is really ugly (and also violates some styling rules I have to follow).

My version is "XeTeX, Version 3.141592653-2.6-0.999994 (TeX Live 2022)"

Maybe you have any other idea how to fix this?

Edit: Specifying the mathfont to Arial in the YAML also does not effect the appearance of the numbers in the reprex table. Using pdflatex just disables the use of all font options and the table numbers as well as the plain text are in the same font family, but not the one I need....

Still working on it. With this reprex I am now reproducing. When I use the pdflatex engine both are in Math mode.

1 Like

Thanks for your effort. I appreciate it.

If you cannot find anything, I guess I have to manually remove all $ signs in my formatted tables. :sweat_smile: But I cannot understand why gt changes the output to Math Mode, since all those are ordinary numbers :confused:

When I take out the pdf-engine it's math-style by default. I'm trying the tab_style approach now.

Update: That didn't work. I went to the *.tex file and moved

\usepackage{fontspec}
\setmainfont[]{Ariel}

to the lines in the tex file immediately above.

The pdf file is the combined effort of quarto, gt, pandoc and xelatex and the tex file is fairly verbose for such small output. I think it's a wonder that it works at all.

You might repose the question on the gt github issues page.

\title{Reprex}

1 Like

Thank you very much for your efforts. I dug into the source code of gt::fmt_number() on GitHub here (from line 163 on). There is a function call of gt:::num_fmt_factory_multi() at line 233, which has the argument use_latex_math_mode = TRUE (see here). This refers to the function gt:::to_latex_math_mode() (see here).

I think if I could change the default behaviour of this function to always pass the argument back, no matter if the context of formatting is in LaTeX, then this would prevent the conversion into math mode by surrounding everything with $ signs.

But I am not that deep into package development and redefining package functions. Do you have suggestions, how to redefine this function to always pass the argument unchanged?

This does it!!!!!

# change the default behaviour of num_fmt_factory_multi

# create the new function
num_fmt_factory_multi_ <- function (pattern, use_latex_math_mode = FALSE, format_fn) 
{
  names(all_contexts) <- all_contexts
  lapply(all_contexts, FUN = function(x) {
    num_fmt_factory(context = x, pattern = pattern, use_latex_math_mode = use_latex_math_mode, 
                    format_fn = format_fn)
  })
}

# https://stackoverflow.com/questions/24331690/modify-package-function
# redefine the function
environment(num_fmt_factory_multi_) <- asNamespace('gt')
assignInNamespace("num_fmt_factory_multi", num_fmt_factory_multi_, ns = "gt")

Running this with source() from inside the .qmd document changes the default of the formatting to not use LaTeX math mode, even though we are in a LaTeX environment. The table now looks like it is supposed to!

I will post the question (and my hacky solution) in the github issue page and see, if there is indeed a preferable solution to my function redefining.

2 Likes

Lesser mortals p-hack; the hard core package hack!

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.