diff --git a/R/context.R b/R/context.R index e444cc4..a116e17 100644 --- a/R/context.R +++ b/R/context.R @@ -97,7 +97,7 @@ cur_group_id <- function() { details <- get_group_details(data) details[, ".group_id"] <- seq_len(nrow(details)) res <- suppressMessages(semi_join(details, res)) - res[, ".group_id", drop = FALSE] + res[, ".group_id"] } #' @description diff --git a/R/mutate.R b/R/mutate.R index 985d572..006d7ea 100644 --- a/R/mutate.R +++ b/R/mutate.R @@ -32,14 +32,25 @@ mutate <- function(.data, ...) { #' @export mutate.default <- function(.data, ...) { conditions <- dotdotdot(..., .impute_names = TRUE) + cond_nms <- names(dotdotdot(..., .impute_names = FALSE)) if (length(conditions) == 0L) return(.data) context$setup(.data) on.exit(context$clean(), add = TRUE) for (i in seq_along(conditions)) { + not_named <- (is.null(cond_nms) || cond_nms[i] == "") res <- eval(conditions[[i]], envir = context$.data) if (!is.list(res)) res <- list(res) - if (is.null(names(res))) names(res) <- names(conditions)[[i]] - context$.data[, names(res)] <- res + res_nms <- names(res) + if (is.data.frame(res)) { + if (not_named) { + context$.data[, res_nms] <- res + } else { + context$.data[[cond_nms[i]]] <- res + } + } else { + if (is.null(res_nms)) names(res) <- names(conditions)[[i]] + context$.data[, names(res)] <- res + } } context$.data } diff --git a/inst/tinytest/test_across.R b/inst/tinytest/test_across.R index fcbbed7..90c4f0a 100644 --- a/inst/tinytest/test_across.R +++ b/inst/tinytest/test_across.R @@ -95,7 +95,7 @@ expect_equal( ) expect_named( - mutate(data.frame(a = 1, b = 2), a = 2, x = across()), + mutate(data.frame(a = 1, b = 2), a = 2, x = across())$x, c("a", "b"), info = "across() retains original ordering" ) diff --git a/inst/tinytest/test_mutate.R b/inst/tinytest/test_mutate.R index aa2d6a4..afe35d1 100644 --- a/inst/tinytest/test_mutate.R +++ b/inst/tinytest/test_mutate.R @@ -76,7 +76,7 @@ expect_equal( { res <- mtcars res <- do.call(rbind, unname(lapply( - split(res, list(res$am , res$cyl)), + split(res, list(res$am, res$cyl)), function(x) { x[, "mpg2"] <- x$mpg * 2 x @@ -137,7 +137,15 @@ expect_identical( df <- data.frame(x = 1) out <- df %>% mutate(y = data.frame(a = x)) -expect_equal(out, data.frame(x = 1, y = data.frame(a = 1)), info = "named data frames are packed") +expect_equal( + out, + { + res <- data.frame(x = 1) + res[["y"]] <- data.frame(a = 1) + res + }, + info = "named data frames are packed" +) gf <- group_by(data.frame(x = 1:2, y = 2), x) out <- mutate(gf, x = 1)