Skip to content

Commit

Permalink
get_dupes() grouped data error fix (#345)
Browse files Browse the repository at this point in the history
* Add check for grouped data, if so remove groups, check for dupes, and reapply groups.
  • Loading branch information
jzadra authored Mar 16, 2020
1 parent f0425ee commit c2e2277
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 1 deletion.
18 changes: 17 additions & 1 deletion R/get_dupes.R
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,18 @@ get_dupes <- function(dat, ...) {

names(dat)[pos] <- names(pos) #allows for renaming within get_dupes() consistent with select()

#Check if dat is grouped and if so, save structure and ungroup temporarily
is_grouped <- dplyr::is_grouped_df(dat)

if(is_grouped) {
dat_groups <- dplyr::group_vars(dat)
dat <- dat %>% dplyr::ungroup()
if(getOption("get_dupes.grouped_warning",TRUE) & interactive()) {
message(paste0("Data is grouped by [", paste(dat_groups, collapse = "|"), "]. Note that get_dupes() is not group aware and does not limit duplicate detection to within-groups, but rather checks over the entire data frame. However grouping structure is preserved.\nThis message is shown once per session and may be disabled by setting options(\"get_dupes.grouped_warning\" = FALSE).")) #nocov
options("get_dupes.grouped_warning" = FALSE) #nocov
}
}

if (rlang::dots_n(...) == 0) { # if no tidyselect variables are specified, check the whole data.frame
var_names <- names(dat)
nms <- rlang::syms(var_names)
Expand Down Expand Up @@ -54,7 +66,11 @@ get_dupes <- function(dat, ...) {
if (nrow(dupes) == 0) {
message(paste0("No duplicate combinations found of: ", paste(var_names, collapse = ", ")))
}
dupes

#Reapply groups if dat was grouped
if(is_grouped) dupes <- dupes %>% dplyr::group_by(!!!rlang::syms(dat_groups))

return(dupes)
}


7 changes: 7 additions & 0 deletions tests/testthat/test-get-dupes.R
Original file line number Diff line number Diff line change
Expand Up @@ -43,3 +43,10 @@ test_that("tidyselect specification matches exact specification", {
expect_equal(mtcars %>% get_dupes(mpg), mtcars %>% get_dupes(-c(cyl, disp, hp, drat, wt, qsec, vs, am ,gear, carb)))
expect_equal(suppressMessages(mtcars %>% select(cyl, wt) %>% get_dupes()), mtcars %>% select(cyl, wt) %>% get_dupes(everything()))
})

test_that("grouped and ungrouped data is handled correctly", {
expect_equal(suppressMessages(mtcars %>% group_by(carb, cyl) %>% get_dupes(mpg, carb)) %>% group_vars(),
mtcars %>% group_by(carb, cyl) %>% group_vars())
expect_equal(suppressMessages(mtcars %>% group_by(carb, cyl) %>% get_dupes(mpg, carb) %>% ungroup()),
mtcars %>% get_dupes(mpg, carb))
})

0 comments on commit c2e2277

Please sign in to comment.