typestar

Counting and proportions in R

Counts, shares within groups, and the tidy way to a percentage table.

library(dplyr)

runs <- tibble(
  lang = c("r", "r", "r", "python", "python", "sql"),
  stars = c(3L, 2L, 3L, 3L, 1L, 2L)
)

print(runs |>
        count(lang, stars) |>
        mutate(share = round(n / sum(n), 3), .by = lang))

print(add_count(runs, lang, name = "lang_runs"))
print(round(proportions(table(runs$stars)), 3))

How it works

  1. count then mutate gives shares in two lines.
  2. add_count keeps every row and adds the group size.
  3. proportions on a table is the base-R equivalent.

Keywords and builtins used here

The run, in numbers

Lines
13
Characters to type
304
Tokens
111
Three-star pace
100 tpm

At the three-star pace of 100 tokens a minute, this run takes about 67 seconds.

Type this snippet

Step 3 of 4 in Grouping, step 16 of 27 in dplyr.

← Previous Next →