format_values | R Documentation |
Formats the results of a summary value so that it can be input into
a (latex) table, such as the output of knitr::kable().
Aims to give a publication-ready result.
Expected input is a numeric vector, with the summary statistic value on
the first place, and on the second/third place the standard deviation or
confidence interval. It is designed to work with the output of functions
such as gm_mean
, median_iqr
and
mean_sd
.
format_values(x, n.digits = 3, latex_output = TRUE, na.rm = FALSE, ...)
x |
numeric values that need to be summarized (for now, only geometric mean + confidence interval is supported) |
n.digits |
digits to preserve in output |
latex_output |
Logical, Whether dollar signs should be used around the output string, for latex formatting in knitr::kable. Make sure to set escape=FALSE in knitr::kable function when using this. |
na.rm |
logical, indicating whether NA values should be excluded |
... |
other parameters, parsed onto function gm_mean |
Inspired by this post.
Character value to input in kable function
df <- data.frame(
V1 = abs(rnorm(n = 1000, mean = 10000, sd = 10000)),
V2 = exp(rnorm(n = 1000, mean = log(10^6), sd = log(10^4))),
V3 = abs(rnorm(n = 1000, mean = 100, sd = 10))
)
#V1: median (IQR)
format_values(median_iqr(df$V1), n.digits = 1)
#V2: geomean (conf)
format_values(gm_mean(df$V2), n.digits = 1)
#V3: mean (SD)
format_values(mean_sd(df$V3), n.digits = 1)
## illustrate how to use summary tables:
library(dplyr)
library(knitr)
library(kableExtra)
# create dummy data, with some variables having much higher average values
# than others, to illustrate the use of this function:
table_data <- immune_data %>%
mutate(across(c(Neutrophils, Monocytes), .fns = ~(.+1)*10^5))
summ_table <- immune_data %>%
group_by(Sex) %>%
summarize(
Neutrophils = format_values(gm_mean(Neutrophils)),
Tregs = format_values(gm_mean(Tregs))
)
knitr::kable(summ_table) %>%
kableExtra::kable_styling()
# The function is also helpful to create many summary values at once:
library(tidyr)
table_data_long <- table_data %>%
select(-c(Sex, Batch, Frailty.index)) %>%
tidyr::pivot_longer(col = everything())
summ_table_long <- table_data_long %>%
group_by(name) %>%
summarize(
"Summary value" = format_values(gm_mean(value, offset = 1), n.digits = 2)
)
# offset gives better results when geomean and confidence interval are calculated
# and there are many zeros in the data. See details of the function gm_mean()
# for more information.
knitr::kable(summ_table_long) %>%
kableExtra::kable_styling()
Add the following code to your website.
For more information on customizing the embed code, read Embedding Snippets.