camr_label_stat
A function is proposed with no known current implementation.
It is often desirable to insert various statistics into text (e.g., "The pilot sample (N=30) is characterized by a mean age of 27.21 years (SD=7.85)..."), into column headers, and into figures. It can be difficult to specify these compactly. camr_label_stat
achieves flexibility and compactness, taking a numeric vector and inserting the appropriate statistics using a syntax reminiscent of the glue
package. It offers flexibility to specify defaults for all statistics to be inserted, or an sprintf
specifier can be used, e.g. "{percent, %.3f}"
.
Please test and suggest changes at our next meeting. Let me know if you know of a package that already does something like this.
camr_label_stat <-
function (vdbl, dec=2, label='{mean} ({sd})', na.rm=FALSE, na.replace='NA') {
if (!is.numeric(vdbl)) {
if (is.logical(vdbl))
vdbl <- as.numeric(vdbl)
else
stop('label_m_sd: first argument must be numeric or coercible to numeric.')
}
if (na.rm)
vdbl <- vdbl[!is.na(vdbl)]
for (chr_insertion in str_extract_all(label, '(?<!\\\\)(?<=\\{).*?(?=\\})')[[1]]) {
chr_stat <- str_split(chr_insertion, ',')[[1]]
chr_format <- chr_stat[2]
chr_stat <- chr_stat[1]
dbl_stat <-
switch(
chr_stat,
'n' = length(vdbl),
'mean' = mean(vdbl),
'sd' = sd(vdbl),
'median' = median(vdbl),
'iqr' = IQR(vdbl),
'percent' = sum(vdbl) / length(vdbl),
'p' = sum(vdbl) / length(vdbl),
stop('Requested statistic "', chr_stat, '" is not available.')
)
if (is.na(chr_format))
dbl_stat <- as.character(round(dbl_stat, dec))
else
dbl_stat <- sprintf(chr_format, dbl_stat)
if (is.na(dbl_stat))
dbl_stat <- na.replace
label <- str_replace(label, '(?<!\\\\)\\{.*?\\}', dbl_stat)
}
label
}
Edited by Pascale, Michael Philip