Skip to content

Commit

Permalink
mutate in order when using .by. Closes #166
Browse files Browse the repository at this point in the history
  • Loading branch information
markfairbanks committed Jan 28, 2021
1 parent 37c5f8a commit 495193d
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 2 deletions.
10 changes: 8 additions & 2 deletions R/mutate.R
Original file line number Diff line number Diff line change
Expand Up @@ -74,7 +74,7 @@ mutate..data.frame <- function(.df, ..., .by = NULL) {
# Faster with "by", since the "by" call isn't looped multiple times for each column added
.by <- select_vec_chr(.df, !!.by)

needs_copy <- any(vec_in(names(dots), names(.df)))
needs_copy <- any(names(dots) %in% names(.df))

if (needs_copy) .df <- copy(.df)

Expand All @@ -95,8 +95,14 @@ mutate..data.frame <- function(.df, ..., .by = NULL) {
}

if (length(dots) > 0) {

assign <- map2.(syms(names(dots)), dots, ~ call2("<-", .x, .y))
output <- call2("list", !!!syms(names(dots)))
expr <- call2("{", !!!assign, output)
j <- call2(":=", call2("c", !!!names(dots)), expr)

eval_quo(
.df[, ':='(!!!dots), by = .by],
.df[, !!j, by = .by],
new_data_mask(data_env), env = caller_env()
)
}
Expand Down
9 changes: 9 additions & 0 deletions tests/testthat/test-mutate.R
Original file line number Diff line number Diff line change
Expand Up @@ -105,6 +105,15 @@ test_that("can use .by", {

})

test_that("can mutate in order with .by", {
df <- tidytable(x = rep(1, 3), z = c("a", "a", "b"))

tidytable_df <- df %>%
mutate.(x = x + 1, y = x + 1, .by = z)

expect_equal(tidytable_df$y, rep(3, 3))
})

test_that("modify-by-reference doesn't occur with single val with .by", {
df <- data.table(x = 1:3, y = 1:3)
df %>%
Expand Down

0 comments on commit 495193d

Please sign in to comment.