This function computes the counts and percentages for each level of a factor or categorical variable. It returns a character vector with each level's count and its percentage of the total, formatted to a specified number of decimal places.

count_percent(x, digits = 2)

Arguments

x

A factor or a categorical variable.

digits

An integer indicating the number of decimal places to which the percentages will be rounded. Defaults to 2.

Value

A character vector where each element corresponds to a level of x. Each element is formatted as 'count (percentage%)', where 'count' is the number of occurrences of the level and 'percentage' is the percentage of the total, rounded to digits decimal places.

Examples

levels= LETTERS[1:3]
factor1 <- levels%>%sample(size = 10, replace = TRUE)%>%factor()
count_percent(factor1,1)
#> [1] "4 (40.0%)" "6 (60.0%)"