diff --git a/NEWS.md b/NEWS.md index 9d747e8..ff4414f 100644 --- a/NEWS.md +++ b/NEWS.md @@ -9,6 +9,9 @@ * Reshape now works better with `.` in specification, like `. ~ .` or `x + y ~ .` +* `dcast()` and `acast()` gain a useful error message if you use `value_var` + intead of `value.var` (#16). + # Version 1.2.2 * Fix incompatibility with plyr 1.8 diff --git a/R/cast.r b/R/cast.r index b14d059..62f4762 100644 --- a/R/cast.r +++ b/R/cast.r @@ -92,7 +92,11 @@ #' @name cast NULL -cast <- function(data, formula, fun.aggregate = NULL, ..., subset = NULL, fill = NULL, drop = TRUE, value.var = guess_value(data)) { +cast <- function(data, formula, fun.aggregate = NULL, ..., subset = NULL, fill = NULL, drop = TRUE, value.var = guess_value(data), value_var) { + + if (!missing(value_var)) { + stop("Please use value.var instead of value_var.", call. = FALSE) + } if (!is.null(subset)) { include <- data.frame(eval.quoted(subset, data)) @@ -108,19 +112,19 @@ cast <- function(data, formula, fun.aggregate = NULL, ..., subset = NULL, fill = # Compute labels and id values ids <- lapply(vars, id, drop = drop) - + # Empty specifications (.) get repeated id is_empty <- vapply(ids, length, integer(1)) == 0 empty <- structure(rep(1, nrow(data)), n = 1L) ids[is_empty] <- rep(list(empty), sum(is_empty)) - + labels <- mapply(split_labels, vars, ids, MoreArgs = list(drop = drop), SIMPLIFY = FALSE, USE.NAMES = FALSE) labels[is_empty] <- rep(list(data.frame(. = ".")), sum(is_empty)) - + overall <- id(rev(ids), drop = FALSE) n <- attr(overall, "n") - + # Aggregate duplicates if (any(duplicated(overall)) || !is.null(fun.aggregate)) { if (is.null(fun.aggregate)) { @@ -145,10 +149,10 @@ cast <- function(data, formula, fun.aggregate = NULL, ..., subset = NULL, fill = ordered[is.na(ordered)] <- fill } } - + ns <- vapply(ids, attr, double(1), "n") dim(ordered) <- ns - + list( data = ordered, labels = labels diff --git a/inst/tests/test-cast.r b/inst/tests/test-cast.r index 610d57b..85043da 100644 --- a/inst/tests/test-cast.r +++ b/inst/tests/test-cast.r @@ -185,7 +185,14 @@ test_that(". ~ . returns single value", { test_that("drop = TRUE retains NA values", { df <- data.frame(x = 1:5, y = c(letters[1:4], NA), value = 5:1) out <- dcast(df, x + y ~ .) - + expect_equal(dim(out), c(5, 3)) - expect_equal(out$., 5:1) -}) \ No newline at end of file + expect_equal(out$., 5:1) +}) + +test_that("useful error message if you use value_var", { + expect_error(dcast(mtcars, vs ~ am, value_var = "cyl"), + "Please use value.var", fixed = TRUE) + expect_equal(dim(dcast(mtcars, vs ~ am, value.var = "cyl")), c(2, 3)) + +})