Uses as.numeric()
to force a numeric value and then formats prettily
for easy presentation in console messages, reports, or dashboards.
This rounds to 2 decimal places by default, and adds in comma separators.
Expect that this will commonly be used for adding the pound symbol, the percentage symbol, or to have a +/- prefixed based on the value.
If applying over multiple or unpredictable values and you want to preserve
a non-numeric symbol such as "x" or "c" for data not available, use the
ignore_na = TRUE
argument to return those values unaffected.
If you want to customise what NA values are returned as, use the alt_na
argument.
This function silences the warning around NAs being introduced by coercion.
Usage
pretty_num(
value,
prefix = "",
gbp = FALSE,
suffix = "",
dp = 2,
ignore_na = FALSE,
alt_na = FALSE
)
Arguments
- value
value to be prettified
- prefix
prefix for the value, if "+/-" then it will automatically assign + or - based on the value
- gbp
whether to add the pound symbol or not, defaults to not
- suffix
suffix for the value, e.g. "%"
- dp
number of decimal places to round to, 2 by default
- ignore_na
whether to skip function for strings that can't be converted and return original value
- alt_na
alternative value to return in place of NA, e.g. "x"
See also
comma_sep()
round_five_up()
as.numeric()
Other prettying functions:
pretty_filesize()
,
pretty_time_taken()
Examples
# On individual values
pretty_num(5789, gbp = TRUE)
#> [1] "£5,789"
pretty_num(564, prefix = "+/-")
#> [1] "+564"
pretty_num(567812343223, gbp = TRUE, prefix = "+/-")
#> [1] "+£567.81 billion"
pretty_num(11^9, gbp = TRUE, dp = 3)
#> [1] "£2.358 billion"
pretty_num(-11^8, gbp = TRUE, dp = -1)
#> [1] "-£210 million"
pretty_num("56.089", suffix = "%")
#> [1] "56.09%"
pretty_num("x")
#> [1] NA
pretty_num("x", ignore_na = TRUE)
#> [1] "x"
pretty_num("nope", alt_na = "x")
#> [1] "x"
# Applied over an example vector
vector <- c(3998098008, -123421421, "c", "x")
unlist(lapply(vector, pretty_num))
#> [1] "4 billion" "-123.42 million" NA NA
unlist(lapply(vector, pretty_num, prefix = "+/-", gbp = TRUE))
#> [1] "+£4 billion" "-£123.42 million" NA NA
# Return original values if NA
unlist(lapply(vector, pretty_num, ignore_na = TRUE))
#> [1] "4 billion" "-123.42 million" "c" "x"
# Return alternative value in place of NA
unlist(lapply(vector, pretty_num, alt_na = "z"))
#> [1] "4 billion" "-123.42 million" "z" "z"