My main goal is to build a table in R Markdown where the columns are decimal aligned. I tried one method which caused a lot of bugs which I document below. But if you know of a better way please let me know.
So the way I tried to solve this was to follow this tutorial (see page 29 for details).
This is my R Markdown code
---
title: "Table of Means"
author: "Kate Champion"
date: "2025-10-16"
output: pdf_document
header-includes:
- \usepackage{booktabs}
- \usepackage{siunitx}
- \newcolumntype{d}{S[table-format=3.2]}
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
library(tidyverse)
library(kableExtra)```
## Table of Means
```{r, echo=FALSE}
means_table = read_rds() #This was data from previous analysis which is too complicated to redo here
means_table = means_table %>%
select(-group)
names(means_table) <- c("{ var_name }", "{ num_obs }", "{ mean }", "{ sd }", "{ min }", "{ max }")
print(means_table) #Only had this for debugging
kable(means_table,
"latex", booktabs =T,
col.names = c(" ", "Number of Obs", "Mean", "SD", "Min", "Max"),
align = "lcccdd") %>%
kable_styling(full_width = F, position = "center", latex_options = "hold_position") %>%
group_rows("Realized", 1, 4) %>%
group_rows("Outcomes", 5, 6)```
This is what the input data table looked like
Currently this markdown will render but I can only get the Min and Max columns to be decimal aligned. To get all the numeric columns aligned I need to set align = "lddddd". However, when I try and change the alignment I get the following errors:
! Package siunitx Error: Invalid number 'e'. when I try and decimal align Number of Obs or Mean
! Package siunitx Error: Invalid number 'D' when I try to align SD
I understand that this is an issue with siunitx thinking there is a character value in the column but I don't understand where its coming from. I thought maybe it was driven by some sort of automatic scientific notation but the values of min and max are not on such a different scale from num obs, mean or sd. I even tried limiting scientific notation with options(scipen = 999) but that didn't fix the issue. The values are dbl's except for num_obs which is int so they are already numeric!
Any suggestions for why siunitx might be making this error and how to get Latex and kable to place together would be appreciated.
