Format count + percent cells to a uniform display width
Source:R/format_count_pct.R
fmt_count_pct.RdReturns each pair (count[i], pct[i]) as a padded "n (xx.x)"
string suitable for monospaced clinical TFL alignment. The four
width branches match the convention in the rtfreporter Issue #2
reference helper.
Usage
fmt_count_pct(
count,
pct,
pct_unit = c("fraction", "percent"),
nbsp = " ",
pct_sign = FALSE,
na = "",
rounding = NULL
)Arguments
- count
Integer / numeric vector of counts. A
0count produces the count-only branch (no parentheses); a missing count produces thenatoken instead.- pct
Numeric vector of percentages. By default expressed as a fraction in
[0, 1]; passpct_unit = "percent"if your values are already in[0, 100]. Recycled againstcountif one argument is length 1. A fraction above 1 says once a session that the values look like percentages (5prints as500).- pct_unit
Either
"fraction"(default,0..1) or"percent"(0..100).- nbsp
Character used to replace the padding spaces. Default is the non-breaking space (Unicode code point U+00A0) so that RTF and Word do not collapse leading whitespace. Pass
" "(regular space) for plain-text output.- pct_sign
Logical (default
FALSE). WhenTRUE, a literal%is placed before the closing parenthesis (e.g." 14 (50.0%)") and every branch is one character wider so the)still aligns.- na
Text to print when the count is missing (
NA, orNaN– R counts it as missing). Right-justified in the count field, so its right edge lands on the ones digit, then padded to the branch width. The default""returns an empty cell. A missing percent alongside a real count is not missing data: the count still prints, on its own.Inf/-Infcounts print as"Inf"/"-Inf"– an infinity means a division by zero upstream, and hiding it would hide the bug.- rounding
How the percent is rounded to one decimal:
"r"(half to even) or"sas"(half away from zero).NULL, the default, readsgetOption("rtfreporter.rounding"); seeround_num().1/16is6.25%, printed"6.2"under"r"and"6.3"under"sas".
Details
fmt_count_pct() was called format_count_pct(), the one cell formatter
not named fmt_: the old name is deprecated (it says so once a session
and still works) and is removed in 0.9.0, the first CRAN release.
See also
as_rtftables(align_count_pct = TRUE) (the built-in cell format
"count_pct") for the same widths starting from already-formatted
strings.
Examples
# Fractions (the default)
fmt_count_pct(c(5L, 14L, 30L), c(0.05, 0.50, 1.00))
#> [1] " 5 (5.0)" " 14 (50.0)" " 30 (100)"
# Percent values
fmt_count_pct(c(5L, 14L, 30L), c(5, 50, 100), pct_unit = "percent")
#> [1] " 5 (5.0)" " 14 (50.0)" " 30 (100)"
# Plain spaces if the output is going to plain text rather than RTF
fmt_count_pct(7L, 0.333, nbsp = " ")
#> [1] " 7 (33.3)"
# A missing count, shown as "-" under the ones digit
fmt_count_pct(c(5L, NA), c(0.05, NA), na = "-", nbsp = " ")
#> [1] " 5 (5.0)" " - "