Skip to content

Commit

Permalink
Behaviour empty behaviour for complete() and expand()
Browse files Browse the repository at this point in the history
Fixes #331
  • Loading branch information
hadley committed Nov 20, 2017
1 parent 5b81db1 commit b26f91e
Show file tree
Hide file tree
Showing 5 changed files with 27 additions and 1 deletion.
4 changes: 4 additions & 0 deletions NEWS.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,9 @@
# tidyr 0.7.2.9000

* `complete()` with zero-length completions returns original input (#331).

* `expand()` with empty input gives empty data frame instead of `NULL` (#331).

* `uncount()` performs the inverse operation of `dplyr::count()` (#279)

* `spread()` now consistently returns 0 row outputs for 0 row inputs (#269).
Expand Down
3 changes: 3 additions & 0 deletions R/complete.R
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,9 @@ complete.default <- function(data, ..., fill = list()) {
#' @export
complete.data.frame <- function(data, ..., fill = list()) {
full <- expand(data, ...)
if (is_empty(full)) {
return(data)
}
full <- dplyr::left_join(full, data, by = names(full))
full <- replace_na(full, replace = fill)

Expand Down
3 changes: 3 additions & 0 deletions R/expand.R
Original file line number Diff line number Diff line change
Expand Up @@ -124,6 +124,9 @@ crossing <- function(...) {
stopifnot(is_list(x))

x <- drop_empty(x)
if (length(x) == 0) {
return(data.frame())
}

is_atomic <- map_lgl(x, is_atomic)
is_df <- map_lgl(x, is.data.frame)
Expand Down
12 changes: 11 additions & 1 deletion tests/testthat/test-complete.R
Original file line number Diff line number Diff line change
Expand Up @@ -16,8 +16,18 @@ test_that("preserves grouping", {

test_that("expands empty factors", {
f <- factor(levels = c("a", "b", "c"))
df <- dplyr::data_frame(one = f, two = f)
df <- tibble(one = f, two = f)

expect_equal(nrow(complete(df, one, two)), 9)
expect_equal(ncol(complete(df, one, two)), 2)
})

test_that("empty expansion returns original", {
df <- tibble(x = character())
rs <- complete(df, y = integer())
expect_equal(rs, df)

df <- tibble(x = 1:4)
rs <- complete(df, y = integer())
expect_equal(rs, df)
})
6 changes: 6 additions & 0 deletions tests/testthat/test-expand.R
Original file line number Diff line number Diff line change
Expand Up @@ -63,6 +63,12 @@ test_that("zero length numeric & character inputs are automatically dropped", {
expect_equal(crossing(x = tb$x, y = character()), tb)
})

test_that("zero length input gives zero length output", {
tb <- tibble(x = character())
expect_equal(expand(tb, x), tibble())
expect_equal(expand(tb, y = NULL), tibble())
})

test_that("zero length factor inputs are completed by expand & crossing, dropped by nesting", {
tb <- tibble::tibble(x = 1:2)
emptyfactor <- factor(levels = c("a","b"))
Expand Down

0 comments on commit b26f91e

Please sign in to comment.