Skip to content

Commit

Permalink
Column renames in count()
Browse files Browse the repository at this point in the history
  • Loading branch information
krlmlr committed Aug 6, 2023
1 parent 681a9c5 commit beafa5b
Show file tree
Hide file tree
Showing 4 changed files with 21 additions and 4 deletions.
5 changes: 3 additions & 2 deletions R/count.R
Original file line number Diff line number Diff line change
Expand Up @@ -28,11 +28,12 @@ count.duckplyr_df <- function(x, ..., wt = NULL, sort = FALSE, name = NULL, .dro
rel <- duckdb_rel_from_df(x)

groups <- rel_translate_dots(by, x)
aggregates <- list(rel_translate(as_quosure(n, baseenv()), x, alias = name))
aggregates <- list(rel_translate(n, x, alias = name))

out_rel <- rel_aggregate(rel, groups, unname(aggregates))
if (length(groups) > 0) {
out_rel <- rel_order(out_rel, groups)
sort_cols <- nexprs(names(groups))
out_rel <- rel_order(out_rel, sort_cols)
}

out <- rel_to_df(out_rel)
Expand Down
4 changes: 4 additions & 0 deletions R/project.R
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,10 @@ nexprs_from_loc <- function(names, loc) {
map2(names[loc], names(loc), ~ relexpr_reference(.x, alias = .y))
}

nexprs <- function(names) {
map(names, ~ relexpr_reference(.x, alias = .x))
}

exprs_project <- function(rel, exprs, .data) {
out_rel <- rel_project(rel, exprs)
out <- rel_to_df(out_rel)
Expand Down
10 changes: 8 additions & 2 deletions R/relational.R
Original file line number Diff line number Diff line change
Expand Up @@ -57,7 +57,13 @@ rel_translate <- function(
need_window = FALSE,
names_data = names(data)
) {
env <- quo_get_env(quo)
if (is_expression(quo)) {
expr <- quo
env <- baseenv()
} else {
expr <- quo_get_expr(quo)
env <- quo_get_env(quo)
}

used <- character()

Expand Down Expand Up @@ -173,7 +179,7 @@ rel_translate <- function(
)
}

out <- do_translate(quo_get_expr(quo))
out <- do_translate(expr)

if (!is.null(alias) && !identical(alias, "")) {
out <- relexpr_set_alias(out, alias)
Expand Down
6 changes: 6 additions & 0 deletions tests/testthat/test-count-tally.R
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,12 @@ test_that("count can sort output", {
expect_equal(out, tibble(x = c(2, 1), n = c(3, 2)))
})

test_that("count can rename grouping columns", {
df <- tibble(x = c(2, 1, 1, 2, 1))
out <- duckplyr_count(df, y = x)
expect_equal(out, tibble(y = c(1, 2), n = c(3, 2)))
})

test_that("informs if n column already present, unless overridden", {
df1 <- tibble(n = c(1, 1, 2, 2, 2))
expect_message(out <- duckplyr_count(df1, n), "already present")
Expand Down

0 comments on commit beafa5b

Please sign in to comment.