Skip to content

Instantly share code, notes, and snippets.

@romainfrancois
Last active December 19, 2018 11:43
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save romainfrancois/6c6f4f75c2940af751a183f19cb43ae8 to your computer and use it in GitHub Desktop.
Save romainfrancois/6c6f4f75c2940af751a183f19cb43ae8 to your computer and use it in GitHub Desktop.
distinct with incomparable
library(dplyr, warn.conflicts = FALSE)
distinct2 <- function(df, predicate_incomparable, ...) {
predicate_incomparable <- enquo(predicate_incomparable)
# rows for which the predicate os true for at least one variable
incomparables <- filter_all(df, any_vars(!!predicate_incomparable))
# rows for which the predicate is false for all variables
comparables <- filter_all(df, all_vars(!(!!predicate_incomparable)))
bind_rows(
distinct(comparables, ...),
incomparables
)
}
df <- tibble(
a = c(1 , 1 , 2, NA, 2, 2, 2),
b = c(NA, NA, 1, 1 , 2, 2, 1),
c = rep(1, 7),
)
df
#> # A tibble: 7 x 3
#> a b c
#> <dbl> <dbl> <dbl>
#> 1 1 NA 1
#> 2 1 NA 1
#> 3 2 1 1
#> 4 NA 1 1
#> 5 2 2 1
#> 6 2 2 1
#> 7 2 1 1
distinct2(df, is.na(.))
#> # A tibble: 5 x 3
#> a b c
#> <dbl> <dbl> <dbl>
#> 1 2 1 1
#> 2 2 2 1
#> 3 1 NA 1
#> 4 1 NA 1
#> 5 NA 1 1
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment