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
countthenmutategives shares in two lines.add_countkeeps every row and adds the group size.proportionson a table is the base-R equivalent.
Keywords and builtins used here
add_countccountlibrarymutateprintproportionsroundsumtabletibble
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.
Step 3 of 4 in Grouping, step 16 of 27 in dplyr.