diff --git a/NEWS.md b/NEWS.md index 4f5c2e55..190ad7a7 100644 --- a/NEWS.md +++ b/NEWS.md @@ -1,5 +1,8 @@ # tidyr (development version) +* `unchop()` produces a more helpful error message when columns cannot be cast + to `ptype` (@mgirlich, #1477). + * `expand_grid()` gains a new `.vary` argument, allowing users to control whether the first column varies fastest or slowest (#1543, @JamesHWade). diff --git a/R/chop.R b/R/chop.R index f777668b..1b411913 100644 --- a/R/chop.R +++ b/R/chop.R @@ -254,8 +254,14 @@ df_unchop <- function(x, ..., ptype = NULL, keep_empty = FALSE, error_call = cal col_sizes <- x_sizes[[i]] if (!col_is_list) { + # Optimize rare non list-cols if (!is_null(col_ptype)) { - col <- vec_cast(col, col_ptype, x_arg = col_name, call = error_call) + col <- vec_cast( + x = col, + to = col_ptype, + x_arg = col_name, + call = error_call + ) } out_cols[[i]] <- vec_slice(col, out_loc) next @@ -267,7 +273,12 @@ df_unchop <- function(x, ..., ptype = NULL, keep_empty = FALSE, error_call = cal row_recycle <- col_sizes != sizes col[row_recycle] <- map2(col[row_recycle], sizes[row_recycle], vec_recycle, call = error_call) - col <- list_unchop(col, ptype = col_ptype) + col <- list_unchop( + x = col, + ptype = col_ptype, + error_arg = col_name, + error_call = error_call + ) if (is_null(col)) { # This can happen when both of these are true: diff --git a/tests/testthat/_snaps/chop.md b/tests/testthat/_snaps/chop.md index 920ee58a..a6d581da 100644 --- a/tests/testthat/_snaps/chop.md +++ b/tests/testthat/_snaps/chop.md @@ -11,6 +11,14 @@ Error in `chop()`: ! `cols` is absent but must be supplied. +# incompatible ptype mentions the column (#1477) + + Code + unnest(df, data, ptype = list(data = integer())) + Condition + Error in `unnest()`: + ! Can't convert `data[[2]]` to . + # incompatible sizes are caught Code diff --git a/tests/testthat/_snaps/unnest.md b/tests/testthat/_snaps/unnest.md index 2b3ff0e0..d470b386 100644 --- a/tests/testthat/_snaps/unnest.md +++ b/tests/testthat/_snaps/unnest.md @@ -31,7 +31,7 @@ (expect_error(unnest(df, x))) Output - Error in `list_unchop()`: + Error in `unnest()`: ! Can't combine `x[[1]]` and `x[[2]]` . # unnest() advises on outer / inner name duplication diff --git a/tests/testthat/test-chop.R b/tests/testthat/test-chop.R index a6469b8b..6490dca6 100644 --- a/tests/testthat/test-chop.R +++ b/tests/testthat/test-chop.R @@ -228,6 +228,14 @@ test_that("`ptype = list()` uses list ptype", { ) }) +test_that("incompatible ptype mentions the column (#1477)", { + df <- tibble(data = list(1, "2")) + + expect_snapshot(error = TRUE, { + unnest(df, data, ptype = list(data = integer())) + }) +}) + test_that("unchopping a bare empty list results in unspecified()", { df <- tibble(x = integer(), y = list()) expect <- tibble(x = integer(), y = unspecified())