Skip to contents

Compute the percentage based on one or multiple variables.

Usage

calc_perc(df, grp_var, main_var = NULL)

Arguments

df

A single data.frame

grp_var

The grouping variable(s) based on which the percentages will be computed

main_var

An optional variable, when provided, will be utilized to compute the percentage for each of its own levels

Value

A data.frame summarizing the counts and percentages within groups. The output is arranged in descending order of counts within each group.

Examples


#without main_var
calc_perc(mtcars,grp_var = c(cyl,vs))
#> # A tibble: 5 × 4
#>     cyl    vs     n  perc
#>   <dbl> <dbl> <int> <dbl>
#> 1     8     0    14 43.8 
#> 2     4     1    10 31.2 
#> 3     6     1     4 12.5 
#> 4     6     0     3  9.38
#> 5     4     0     1  3.12

#main_var within grp_var
calc_perc(mtcars,grp_var = c(cyl,vs),main_var = vs)
#> # A tibble: 5 × 4
#> # Groups:   vs [2]
#>      vs   cyl     n  perc
#>   <dbl> <dbl> <int> <dbl>
#> 1     0     8    14 77.8 
#> 2     0     6     3 16.7 
#> 3     0     4     1  5.56
#> 4     1     4    10 71.4 
#> 5     1     6     4 28.6 

#main_var not within grp_var
calc_perc(mtcars,grp_var = c(cyl),main_var = vs)
#> # A tibble: 5 × 4
#> # Groups:   vs [2]
#>      vs   cyl     n  perc
#>   <dbl> <dbl> <int> <dbl>
#> 1     0     8    14 77.8 
#> 2     0     6     3 16.7 
#> 3     0     4     1  5.56
#> 4     1     4    10 71.4 
#> 5     1     6     4 28.6