diff --git a/NAMESPACE b/NAMESPACE index 91e8700fe..94a224678 100644 --- a/NAMESPACE +++ b/NAMESPACE @@ -10,6 +10,7 @@ S3method(as_tibble,dtplyr_step) S3method(auto_copy,dtplyr_step) S3method(collect,dtplyr_step) S3method(compute,dtplyr_step) +S3method(count,data.table) S3method(count,dtplyr_step) S3method(dim,dtplyr_step) S3method(dim,dtplyr_step_first) @@ -79,6 +80,8 @@ S3method(slice_tail,dtplyr_step) S3method(summarise,data.table) S3method(summarise,dtplyr_step) S3method(tail,dtplyr_step) +S3method(tally,data.table) +S3method(tally,dtplyr_step) S3method(tbl_vars,dtplyr_step) S3method(tbl_vars,foo) S3method(transmute,data.table) @@ -135,6 +138,7 @@ importFrom(dplyr,slice_min) importFrom(dplyr,slice_sample) importFrom(dplyr,slice_tail) importFrom(dplyr,summarise) +importFrom(dplyr,tally) importFrom(dplyr,tbl_vars) importFrom(dplyr,transmute) importFrom(dplyr,ungroup) diff --git a/NEWS.md b/NEWS.md index 528acc7b8..6a39b5ca6 100644 --- a/NEWS.md +++ b/NEWS.md @@ -1,5 +1,9 @@ # dtplyr (development version) +* Loading `dtplyr` doesn't break the `count()` method on data.tables anymore (@mgirlich, #201). + +* `tally()` is now translated (@mgirlich, #201). + * More tidyr verbs are in the process of being added: * `drop_na()` (@markfairbanks, #194) diff --git a/R/count.R b/R/count.R index 46f86730c..ed730ce97 100644 --- a/R/count.R +++ b/R/count.R @@ -21,8 +21,20 @@ count.dtplyr_step <- function(.data, ..., wt = NULL, sort = FALSE, name = NULL) out <- .data } - wt <- enexpr(wt) - if (is.null(wt)) { + tally(out, wt = !!enquo(wt), sort = sort, name = name) +} + +#' @export +count.data.table <- function(.data, ...) { + .data <- lazy_dt(.data) + count(.data, ...) +} + +#' @importFrom dplyr tally +#' @export +tally.dtplyr_step <- function(.data, wt = NULL, sort = FALSE, name = NULL) { + wt <- enquo(wt) + if (quo_is_null(wt)) { n <- expr(n()) } else { n <- expr(sum(!!wt, na.rm = TRUE)) @@ -34,7 +46,7 @@ count.dtplyr_step <- function(.data, ..., wt = NULL, sort = FALSE, name = NULL) abort("`name` must be a string") } - out <- summarise(out, !!name := !!n) + out <- summarise(.data, !!name := !!n) if (sort) { out <- arrange(out, desc(!!sym(name))) @@ -42,3 +54,9 @@ count.dtplyr_step <- function(.data, ..., wt = NULL, sort = FALSE, name = NULL) out } + +#' @export +tally.data.table <- function(.data, ...) { + .data <- lazy_dt(.data) + tally(.data, ...) +} diff --git a/tests/testthat/test-count.R b/tests/testthat/test-count.R index f5bd6a342..e88aa4f2d 100644 --- a/tests/testthat/test-count.R +++ b/tests/testthat/test-count.R @@ -41,3 +41,11 @@ test_that("can sort", { tibble(x = c(2, 1), n = c(10, 3)) ) }) + +test_that("tally works", { + dt <- lazy_dt(data.table(x = c(1, 1, 1, 2)), "DT") + expect_equal( + dt %>% group_by(x) %>% tally() %>% collect(), + tibble(x = c(1, 2), n = c(3, 1)) + ) +})