propf: Calculate and format proportion

View source: R/stats.R

propfR Documentation

Calculate and format proportion

Description

This is a simple utility that takes an input vector (character or factor) and calculates proportion of elements in the vector that equal a user-specified value.

Usage

propf(x, level = "1", digits = 2, percent = TRUE, ...)

Arguments

x

Vector for which the proportion should of 'level' values should be calculated

level

The non-reference level of interest; default is 1

digits

The number of decimal places to use; default is 2

percent

Boolean indicating whether or not the formatted proportion should be converted to percentage; default is TRUE

...

Additional arguments passed to formatC

Details

The function works by first converting the input vector "x" to a factor, then the counting the occurrence of the "level" value, calculating the proportion, and finally formatting the output as count and proportion or percentage in parentheses. The default value for "level" is 1, which assumes the user is interested in calculating the proportion of non-reference values in a binary variable. This utility works just as well with non-binary variables, and the user can issue the function call on the same vector with different values of "level" if there are > 1 non-reference proportions of interest.

Value

A character vector of length 1 formatted as either "count (proportion)" or "count (percentage%)" depending on the input to "percent" argument. In either case the formatting can be further customized using arguments to base::formatC.

Examples



dogs <- c("dog","dog","dog")
cats <- c("cat","cat")
rats <- c("rat","rat","rat","rat","rat")
animals <- c(dogs,cats,rats)

propf(animals, level = "rat")
propf(animals, level = "rat", decimal.mark = ",")
propf(animals, level = "dog", percent = FALSE)
propf(animals, level = "dog", percent = FALSE, drop0trailing = TRUE)


vpnagraj/yawp documentation built on March 31, 2022, 9:56 a.m.