Skip to content

Commit

Permalink
Useful error message if you use value_var.
Browse files Browse the repository at this point in the history
Closes hadley#16
  • Loading branch information
hadley authored and duncandoo committed Jun 23, 2014
1 parent e0271cf commit b3fa41c
Show file tree
Hide file tree
Showing 3 changed files with 24 additions and 10 deletions.
3 changes: 3 additions & 0 deletions NEWS.md
Expand Up @@ -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
Expand Down
18 changes: 11 additions & 7 deletions R/cast.r
Expand Up @@ -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))
Expand All @@ -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)) {
Expand All @@ -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
Expand Down
13 changes: 10 additions & 3 deletions inst/tests/test-cast.r
Expand Up @@ -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)
})
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))

})

0 comments on commit b3fa41c

Please sign in to comment.