Uses a formula interface to specify how the proportions are to be calculated.

df_props(formula, data, as.percent = FALSE, ..., wide = FALSE,
  margins = FALSE, format = c("proportion", "percent", "count"))

Arguments

formula

the formula describing the relationship

data

a data frame (or you can pipe this in)

as.percent

show proportions in percent (e.g. multiply by 100)

...

statistics functions to be applied to the data, e.g. mean, sd, confidence(0.95)

wide

reformat the output as a cross-tabulation. This makes sense only when there are just two variables

margins

show the marginal probabilities. Makes the most sense if wide = TRUE.

format

Use just for internal purposes.

Details

Using | in the formula specifies a conditional proportion

  • ~ A : proportion of cases in each level of A

  • ~ A + B: joint proportion: each level of A crossed with B

  • ~ A | B: conditional proportion: for each level of B, what fraction are in each level of A

  • A ~ B: another way of specifying the conditional proportion

Examples

df_props(mtcars, ~ cyl + gear)
#> # A tibble: 9 x 3 #> # Groups: cyl [3] #> cyl gear proportion #> * <fct> <fct> <dbl> #> 1 4 3 0.0312 #> 2 6 3 0.0625 #> 3 8 3 0.375 #> 4 4 4 0.25 #> 5 6 4 0.125 #> 6 8 4 0 #> 7 4 5 0.0625 #> 8 6 5 0.0312 #> 9 8 5 0.0625
df_props(mtcars, ~ cyl | gear)
#> # A tibble: 9 x 3 #> # Groups: cyl [3] #> cyl gear proportion #> * <fct> <fct> <dbl> #> 1 4 3 0.0667 #> 2 6 3 0.133 #> 3 8 3 0.8 #> 4 4 4 0.667 #> 5 6 4 0.333 #> 6 8 4 0 #> 7 4 5 0.4 #> 8 6 5 0.2 #> 9 8 5 0.4
df_props(mtcars, ~ cyl + gear, wide = TRUE)
#> cyl gear_3 gear_4 gear_5 #> 1 4 0.03125 0.250 0.06250 #> 2 6 0.06250 0.125 0.03125 #> 3 8 0.37500 0.000 0.06250
df_props(mtcars, ~ cyl + gear, margins = TRUE)
#> Warning: Switching to wide mode to display marginals.
#> cyl gear_3 gear_4 gear_5 gear_Total #> 1 4 0.03125 0.250 0.06250 0.34375 #> 2 6 0.06250 0.125 0.03125 0.21875 #> 3 8 0.37500 0.000 0.06250 0.43750 #> 4 Total 0.46875 0.375 0.15625 1.00000
df_props(mtcars, ~ cyl | gear, margins = TRUE)
#> Warning: Switching to wide mode to display marginals.
#> cyl gear_3 gear_4 gear_5 #> 1 4 0.06666667 0.6666667 0.4 #> 2 6 0.13333333 0.3333333 0.2 #> 3 8 0.80000000 0.0000000 0.4 #> 4 Total 1.00000000 1.0000000 1.0