rms-wordr-markdownhuxtable

Scientific formats, subscripts and superscripts in RMarkdown table (docx output)


Let's say I have the following rmd:

---
title: "Table won't work"
author: "Exhausted student"
date: "2022/01/28"
output: 
  bookdown::word_document2
---

```{r table, echo=F, warning=F, message=F}
library(tidyverse)
a <- tibble(
  constants = c("c", "NA", "h", "e", "H2O"),
  values = c(2.998e8, 6.022e23, 6.626e-34, -1.602e-19, 18.02)
)

knitr::kable(a, digits = 35)
```

which produces this table in Word.

The Problem

I need the scientific format to use superscripts and multiply sign (i.e. 2.998 × 108), and some cells requires subscript (e.g. NA and H2O).

The final table should look like this. How can I do that?

What I've tried/would never try

  1. huxtable package and its markdown() function: I managed to format some contents as H~2~O, then enable markdown across table by huxtable(a) %>% `markdown<-`(TRUE). Which did not recognize the syntax, and apparently would not work in forseeable future according to the author.
  2. flextable and as_sub(): Produces right format. I pass the lables to flextable::compose(), where the labels were something like as_paragraph(list_values = list("H", as_sub("2"), "O"). The code is obviously too lengthy; plus i have to manipulate cells one-by-one. Technically still doable, but I do have tables with 100+ cells needed formatting.
  3. Output first, format in Word later: Again, needed manipulation one-by-one. Would be an option if it would work everything out automatically.
  4. Convincing the school bureaucrats to accept html/pdf/latex as output: this is forever an impossible option.
  5. Format outside word then export formatted table as image: strictly forbidden in the reports.

Edit: the table works now! Great thanks to Maël's answer, but please check my own findings to see my final result:

well-formatted table


Solution

  • You can use tildes (~) to put in subscript and carets (^) for superscripts; and use sprintf to get the expected digit format:

    ---
    title: "Table won't work"
    author: "Exhausted student"
    date: "2022/01/28"
    output: 
      bookdown::word_document2
    ---
    
    ```{r table, echo=F, warning=F, message=F}
    library(tidyverse)
    
    expSup <- function(x, digits=3) {
      sprintf(paste0("%05.", digits, "f x 10^%d^"), x/10^floor(log10(abs(x))), floor(log10(abs(x))))
    }
    
    a <- tibble(
      constants = c("c", "N~A~", "h", "e", "H~2~0"),
      values = expSup(c(2.998e8, 6.022e-23, 6.626e-34, -1.602e-19, 18.02))
    )
    
    knitr::kable(a)
    ```
    

    enter image description here