If you can accept an +-
symbol to display standard deviation in LaTeX, then there is a package qwraps2
with the function mean_sd()
, which calculates and converts the mean and standard deviation to a latex friendly output format. The output can be exported by the package xtable
to LaTeX.
Here is an example code:
(Just for fun, I've added the statistics for Sepal.Length
)
library(tidyverse)
library(xtable)
library(qwraps2)
df <- iris %>%
group_by(Species) %>%
summarize(across(c(Petal.Length,Sepal.Length), mean_sd, digits = 3))
df
Which generates:
`summarise()` ungrouping output (override with `.groups` argument)
# A tibble: 3 x 3
Species Petal.Length Sepal.Length
<fct> <chr> <chr>
1 setosa "1.462 $\\pm$ 0.174" "5.006 $\\pm$ 0.352"
2 versicolor "4.260 $\\pm$ 0.470" "5.936 $\\pm$ 0.516"
3 virginica "5.552 $\\pm$ 0.552" "6.588 $\\pm$ 0.636"
Exporting to LaTeX using xtable
.
df %>%
xtable() %>%
print.xtable(type = "latex",
sanitize.text.function = function(x){x})
Leading to LaTeX code:
% latex table generated in R 3.6.0 by xtable 1.8-4 package
% Mon Jan 11 20:06:07 2021
\begin{table}[ht]
\centering
\begin{tabular}{rlll}
\hline
& Species & Petal.Length & Sepal.Length \\
\hline
1 & setosa & 1.462 $\pm$ 0.174 & 5.006 $\pm$ 0.352 \\
2 & versicolor & 4.260 $\pm$ 0.470 & 5.936 $\pm$ 0.516 \\
3 & virginica & 5.552 $\pm$ 0.552 & 6.588 $\pm$ 0.636 \\
\hline
\end{tabular}
\end{table}
EDIT ---------------
There is actually a way to set parenthesis in mean_sd()
df <- iris %>%
group_by(Species) %>%
summarize(across(c(Petal.Length,Sepal.Length), mean_sd, digits = 3, denote_sd = "paren"))
df
Console output:
`summarise()` ungrouping output (override with `.groups` argument)
# A tibble: 3 x 3
Species Petal.Length Sepal.Length
<fct> <chr> <chr>
1 setosa 1.462 (0.174) 5.006 (0.352)
2 versicolor 4.260 (0.470) 5.936 (0.516)
3 virginica 5.552 (0.552) 6.588 (0.636)