Learn R Programming

dtlg (version 0.0.2)

round_pct: Rounded percentage

Description

round_pct() returns the rounded percentages of x values.

Usage

round_pct(x, digits = 1L, method = c("round", "round_sum"))

Value

A numeric vector of the same length as x with rounded percentages.

Arguments

x

A numeric vector of non-negative values for which you want percentages to be determined and rounded. Missing values (NA) are ignored.

digits

The number of decimal places to round to. Default is 0 (integer rounding).

method

Rounding method: "round" that uses R's base round() or "round_sum" that uses dtlg::round_sum.

Examples

Run this code
x <- c(1 / 3, 1 / 3, 1 / 3)

# Default method ensures precise rounding but total might not be 100%.
round_pct(x = x)
sum(round_pct(x = x))

# You can trade off rounding precision for precision on the total with the
# method `"round_sum"`.
round_pct(x = x, method = "round_sum")
sum(round_pct(x = x, method = "round_sum"))

# Vary the number of decimal places, e.g. increase to three.
round_pct(x = x, digits = 3, method = "round_sum")

# Missing values are ignored.
x <- c(1, 2, NA)
round_pct(x = x, digits = 3)

Run the code above in your browser using DataLab