From e0114f4c02cb27d781db54796eeb6475a707379a Mon Sep 17 00:00:00 2001 From: hadley Date: Thu, 9 Jun 2016 07:18:48 -0500 Subject: [PATCH] Allow spread to work with list cols Fixes #199 --- NEWS.md | 2 ++ R/id.R | 5 +++++ tests/testthat/test-spread.R | 8 ++++++++ 3 files changed, 15 insertions(+) diff --git a/NEWS.md b/NEWS.md index dbb482c28..0d6ebb055 100644 --- a/NEWS.md +++ b/NEWS.md @@ -31,6 +31,8 @@ as "keyvalue". Additionally, if sep is `NULL` missing values will be converted to `` (#68). +* `spread()` works in the presence of list-columns (#199) + * `unnest()` works with non-syntactic names (#190). * `unnest()` gains a `sep` argument. If non-null, this will rename the diff --git a/R/id.R b/R/id.R index 02ec83d7f..f28f77d4c 100644 --- a/R/id.R +++ b/R/id.R @@ -47,6 +47,11 @@ id_var <- function(x, drop = FALSE) { } else if (length(x) == 0) { id <- integer() n <- 0L + } else if (is.list(x)) { + # Sorting lists isn't supported + levels <- unique(x) + id <- match(x, levels) + n <- max(id) } else { levels <- sort(unique(x), na.last = TRUE) id <- match(x, levels) diff --git a/tests/testthat/test-spread.R b/tests/testthat/test-spread.R index 84b4ed291..64b3af333 100644 --- a/tests/testthat/test-spread.R +++ b/tests/testthat/test-spread.R @@ -145,6 +145,14 @@ test_that("complex values are preserved (#134)", { expect_equal(out2$b, 3:4 + 1i) }) +test_that("can spread with nested columns", { + df <- tibble::data_frame(x = c("a", "a"), y = 1:2, z = list(1:2, 3:5)) + out <- spread(df, x, y) + + expect_equal(out$a, 1:2) + expect_equal(out$z, df$z) +}) + test_that("spread gives one column when no existing non-spread vars", { df <- data_frame( key = c("a", "b", "c"),