Skip to content

Instantly share code, notes, and snippets.

@mikmart
Last active February 19, 2018 10:28
Show Gist options
  • Save mikmart/ec8d74de5c34924b7631d7445c2a8a08 to your computer and use it in GitHub Desktop.
Save mikmart/ec8d74de5c34924b7631d7445c2a8a08 to your computer and use it in GitHub Desktop.
Counting and completing, with special behaviour for `grouped_df`
library(tidyverse)
library(rlang)
complete_count <- function(.data, ...) {
UseMethod("complete_count")
}
complete_count.grouped_df <- function(.data, ...) {
grps <- groups(.data)
.data %>%
ungroup() %>%
complete_count(!!!grps, ...) %>%
group_by(!!!grps)
}
complete_count.data.frame <- function(.data, ...) {
dots <- enquos(...)
.data %>%
count(!!!dots) %>%
complete(!!!dots, fill = list(n = 0L))
}
df <- tibble(a = c(1, 1, 2), b = c(3, 4, 5))
# Normally `complete` will just complete within groups
df %>%
group_by(a) %>%
count(b) %>%
complete(b)
#> # A tibble: 3 x 3
#> # Groups: a [2]
#> a b n
#> <dbl> <dbl> <int>
#> 1 1.00 3.00 1
#> 2 1.00 4.00 1
#> 3 2.00 5.00 1
# `complete_count` will complete across groups, too
df %>%
group_by(a) %>%
complete_count(b)
#> # A tibble: 6 x 3
#> # Groups: a [2]
#> a b n
#> <dbl> <dbl> <int>
#> 1 1.00 3.00 1
#> 2 1.00 4.00 1
#> 3 1.00 5.00 0
#> 4 2.00 3.00 0
#> 5 2.00 4.00 0
#> 6 2.00 5.00 1
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment