diff --git a/r/R/dplyr-mutate.R b/r/R/dplyr-mutate.R index a62149f6743..9c41a660b8f 100644 --- a/r/R/dplyr-mutate.R +++ b/r/R/dplyr-mutate.R @@ -75,6 +75,8 @@ mutate.arrow_dplyr_query <- function( # Make a copy of .data, do the aggregations on it, and then left_join on # the group_by variables. agg_query <- as_adq(.data) + agg_query$arrange_vars <- list() + agg_query$arrange_desc <- logical() # These may be computed by .by, make sure they're set agg_query$group_by_vars <- grv agg_query$aggregations <- mask$.aggregations diff --git a/r/R/dplyr-summarize.R b/r/R/dplyr-summarize.R index 7c2a44eec3d..0d44f741a11 100644 --- a/r/R/dplyr-summarize.R +++ b/r/R/dplyr-summarize.R @@ -88,6 +88,8 @@ do_arrow_summarize <- function(.data, ..., .groups = NULL) { # Apply the results to the .data object. # First, the aggregations .data$aggregations <- mask$.aggregations + .data$arrange_vars <- list() + .data$arrange_desc <- logical() # Then collapse the query so that the resulting query object can have # additional operations applied to it out <- collapse.arrow_dplyr_query(.data) diff --git a/r/tests/testthat/test-dplyr-mutate.R b/r/tests/testthat/test-dplyr-mutate.R index 63f69227b28..033d8f32ffb 100644 --- a/r/tests/testthat/test-dplyr-mutate.R +++ b/r/tests/testthat/test-dplyr-mutate.R @@ -775,3 +775,24 @@ test_that("across() does not select grouping variables within transmute()", { "Column `chr` doesn't exist" ) }) + +test_that("mutate() with aggregations after arrange() (GH-45373)", { + compare_dplyr_binding( + .input |> + select(int, chr) |> + arrange(int) |> + mutate(avg_int = mean(int)) |> + collect(), + tbl + ) + # A row limit between arrange() and mutate() still uses the sorted rows + compare_dplyr_binding( + .input |> + select(int, chr) |> + arrange(int) |> + head(3) |> + mutate(max_int = max(int, na.rm = TRUE)) |> + collect(), + tbl + ) +}) diff --git a/r/tests/testthat/test-dplyr-summarize.R b/r/tests/testthat/test-dplyr-summarize.R index bb18c01666e..0e2ce846557 100644 --- a/r/tests/testthat/test-dplyr-summarize.R +++ b/r/tests/testthat/test-dplyr-summarize.R @@ -1336,3 +1336,31 @@ test_that(".by argument", { "Can't supply `\\.by` when `\\.data` is grouped data" ) }) + +test_that("summarize() after arrange() (GH-45373)", { + compare_dplyr_binding( + .input |> + arrange(int) |> + summarize(min_int = min(int, na.rm = TRUE)) |> + collect(), + tbl + ) + compare_dplyr_binding( + .input |> + arrange(dbl) |> + group_by(some_grouping) |> + summarize(total = sum(int, na.rm = TRUE)) |> + arrange(some_grouping) |> + collect(), + tbl + ) + # A row limit between arrange() and summarize() still uses the sorted rows + compare_dplyr_binding( + .input |> + arrange(int) |> + head(3) |> + summarize(max_int = max(int, na.rm = TRUE)) |> + collect(), + tbl + ) +})